全局应用时未调用WebApi操作过滤器依赖项注入

时间:2016-02-25 14:59:34

标签: c# asp.net-web-api dependency-injection unity-container

我有一个简单的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实例时,我得到一个空引用异常。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

尝试

    config.Filters.Add((IExceptionFilter)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(LogExceptionAttribute)));

APPEND

在你发表评论之后,我进一步检查了我的。

我有构造函数依赖

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);
        }
    }
}

所以我的建议是切换到构造函数注入。