无法使用Unity引导程序为ASP.NET Web API nuget包注入System.Web.Http.Filters.ActionFilterAttribute

时间:2013-10-02 05:21:33

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

使用Unity Web API API nuget包的Unity引导程序,我无法使用自定义ActionFilterAttribute类进行依赖注入。

我已经在UnityConfig中注册了这个类型,并且我在其他地方使用它(虽然使用了构造函数注入)但它工作正常。

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<ISettingService, SettingService>();
    ...
}

正在成功调用代码,但实例化对象(settingService)为null。

public class APIKeyValidationAttribute : ActionFilterAttribute
{
    [Dependency]
    public ISettingService settingService { get; set; }

public override void OnActionExecuting(HttpActionContext actionContext)
{
    ...
    if (settingService == null)
    {
        throw new Exception("settingService is null");
    }
    ...
}

我需要做些什么才能让这个工作?我已经搜索了很长时间,只能找到MVC或带有不同依赖注入器的Web API的示例。

1 个答案:

答案 0 :(得分:8)

首先创建一个IFilterProvider,它将执行BuildUp并注入依赖项:

public class UnityActionFilterProvider 
    : ActionDescriptorFilterProvider, IFilterProvider
{
    private readonly IUnityContainer container;

    public UnityActionFilterProvider(IUnityContainer container)
    {
        this.container = container;
    }

    public new IEnumerable<FilterInfo> GetFilters(
        HttpConfiguration configuration, 
        HttpActionDescriptor actionDescriptor)
    {
        var filters = base.GetFilters(configuration, actionDescriptor);

        foreach (var filter in filters)
        {
            container.BuildUp(filter.Instance.GetType(), filter.Instance);
        }

        return filters;
    }
}

然后注册IFilterProvider:

private static void RegisterFilterProviders()
{
    var providers = 
        GlobalConfiguration.Configuration.Services.GetFilterProviders().ToList();

    GlobalConfiguration.Configuration.Services.Add(
        typeof(System.Web.Http.Filters.IFilterProvider),
        new UnityActionFilterProvider(UnityConfig.GetConfiguredContainer()));

    var defaultprovider = providers.First(p => p is ActionDescriptorFilterProvider);

    GlobalConfiguration.Configuration.Services.Remove(
        typeof(System.Web.Http.Filters.IFilterProvider), 
        defaultprovider);
}

我把这个方法放在UnityWebApiActivator类中调用它。