使用 .NET API 上的属性进行依赖注入
·
1 分钟阅读
Available in:
中文
·
English
·
Español
·
Français
·
Deutsch
·
Português
·
한국어
·
日本語
·
Русский
·
العربية
·
हिन्दी
·
Polski
·
Türkçe
·
Bahasa Indonesia
·
Nederlands
依赖注入可能是目前 .NET 上最好的功能之一。在任何可能的情况下,您都不可能不使用它,所以如果您像我一样,您非常希望将它添加到您所做的所有实现中。
过滤器,根据微软官方的文档:
ASP.NET Core 中的过滤器允许代码在请求处理管道中的特定阶段之前或之后运行。
内置过滤器可处理以下任务:
- 授权,防止用户访问未经授权的资源。
- 响应缓存,短路请求管道以返回缓存的响应。
可以创建自定义过滤器来处理横切问题。横切关注点的示例包括错误处理、缓存、配置、授权和日志记录。过滤器避免重复代码。
我经常使用 API,有些东西必须运行每个请求,或者几乎所有请求,所以,理想情况下我们想要做的是使用它加上……依赖注入!
但有时这有点棘手,如果我们想继承 ActionAttribute,它就不会像我们想要的那样工作,所以我们需要使用 TypeFilterAttribute,它让我们在重写 OnActionExecutionAsync 时做一些事情。
我通常创建这个过滤器来进行一些日志记录,所以我们将使用它作为示例:
/// <summary>
/// LoggedQueryAttribute class
/// </summary>
public class LoggedQueryTypeFilterAttribute : TypeFilterAttribute
{
/// <summary>
/// Constructor for <see cref="LoggedQueryTypeFilterAttribute"/>
/// </summary>
public LoggedQueryTypeFilterAttribute() : base(typeof(LoggedQueryFilter))
{
}
/// <summary>
/// LoggedQueryFilter class
/// </summary>
private class LoggedQueryFilter : IAsyncActionFilter
{
/// <summary>
/// <see cref="_loggingService"/> object
/// </summary>
private readonly LoggingService _loggingService;
/// <summary>
/// Constructor for <see cref="LoggedQueryFilter"/>
/// </summary>
/// <param cref="LoggingService" name="loggingService">Parameter for loggingService</param>
public LoggedQueryFilter(LoggingService loggingService)
{
_loggingService = loggingService;
}
/// <summary>
/// OnActionExecutionAsync
/// </summary>
/// <param cref="ActionExecutingContext" name="context">Parameter for context</param>
/// <param cref="ActionExecutionDelegate" name="next">Parameter for next</param>
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
// Get properties
var properties = (Request)context.ActionArguments.First().Value!;
// Get call from context
var call = context.HttpContext.Request.Path.Value!;
// Logging
_loggingService.LogCustomEvent(call);
// Continue call
await next();
}
}
}
逻辑非常简单,我们通过使用 context.ActionArguments.First().Value 访问 context 对象来获取主体,同时我们也通过 context.HttpContext.Request.Path.Value 获取方法调用。
然后我们只需从我们的服务中调用我们的方法,在本例中是 _loggingService.LogCustomEvent(call)。
然后,我们必须调用 await next();,因为管道必须继续。
这是针对属性的,现在,我们实际上必须将此属性包含到方法中。
[LoggedQueryTypeFilterAttribute]
public ActionResult<string> TestFilter()
{
return Ok("Hello world!");
}
希望您喜欢它,如果您有任何疑问或想联系我,请不要犹豫,与我联系!