全局应用时不调用 WebAPI 操作筛选器依赖项注入
本文关键字:依赖 注入 筛选 操作 调用 WebAPI 全局应用 | 更新日期: 2023-09-27 18:36:08
我有一个简单的WebApi操作(异常)过滤器...
public class LogExceptionAttribute : ExceptionFilterAttribute
{
[Dependency]
public ILogger Logger { get; set; }
public override void OnException(HttpActionExecutedContext context)
{
Logger.Fatal(context.Exception, "Critical exception in request to WebApi controller.");
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("Internal Server Error."),
ReasonPhrase = "Critical Exception"
});
}
}
Unity 筛选器提供程序...
public class UnityFilterProvider : IFilterProvider
{
private IUnityContainer _container;
private readonly ActionDescriptorFilterProvider _defaultProvider = new ActionDescriptorFilterProvider();
public UnityFilterProvider(IUnityContainer container)
{
_container = container;
}
public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
{
var attributes = _defaultProvider.GetFilters(configuration, actionDescriptor);
foreach (var attr in attributes)
{
_container.BuildUp(attr.Instance.GetType(), attr.Instance);
}
return attributes;
}
}
以及以下统一配置...
var providers = config.Services.GetFilterProviders().ToList();
config.Services.Add(typeof(IFilterProvider), new UnityFilterProvider(container));
var defaultprovider = providers.Single(i => i is ActionDescriptorFilterProvider);
config.Services.Remove(typeof(IFilterProvider), defaultprovider);
var logger = LogFactory.CreateWebApiLogger();
container.RegisterInstance<ILogger>(logger);
将 [LogException]
属性应用于控制器时,依赖项注入将正常工作,并且 ILogger 实例在异常筛选器中可用。
但是,当我尝试全局配置过滤器时...
config.Filters.Add(new LogExceptionAttribute());
依赖项未解决,并且在尝试从过滤器中访问 ILogger 实例时出现空引用异常。
我错过了什么?
尝试
config.Filters.Add((IExceptionFilter)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(LogExceptionAttribute)));
附加
在你的评论之后,我进一步检查了我的。
我有构造函数依赖项
public class LogExceptionAttribute : ExceptionFilterAttribute, IExceptionFilter
{
private ILogger Logger { get; set; }
public LogExceptionAttribute (ILogger logger)
{
this.Logger = logger;
}
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception != null)
{
this.Logger.LogException(context.Exception);
}
}
}
所以我的建议是切换到构造函数注入。