使用全局Web API过滤器属性的Unity依赖注入

时间:2013-11-05 16:53:42

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

引用此CodePlex unity article我能够使用WebAPI控制器获取过滤器属性,如下所示:

[MyFilterAttribute]
public class TestController : ApiController
{}

但是,如果我想在使用GlobalConfiguration的所有操作中应用我的过滤器属性,它将被剥离注入的依赖项:

public class MyFilterAttribute : ActionFilterAttribute 
{
    [Dependency]
    public MyDependency { get; set; }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
         if (this.MyDependency == null) //ALWAYS NULL ON GLOBAL CONFIGURATIONS
             throw new Exception();
    }
 }

public static class UnityWebApiActivator
    {
        public static void Start() 
        {
            var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());

            GlobalConfiguration.Configuration.DependencyResolver = resolver;

            GlobalConfiguration.Configuration.Filters.Add(new MyFilterAttribute());

            RegisterFilterProviders();
        }

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

是否有更好的地方添加全局配置?

1 个答案:

答案 0 :(得分:13)

问题出现了,因为您要将新的MyFilterAttribute添加到filters集合(即:GlobalConfiguration.Configuration.Filters.Add(**new MyFilterAttribute()**)),而不是通过Unity解析的实例。由于Unity不参与实例的创建,因此它没有用于注入依赖项的触发器。只需通过Unity解析实例就可以解决这个问题。 e.g:

GlobalConfiguration.Configuration.Filters.Add((MyFilterAttribute)resolver.GetService(typeof(MyFilterAttribute()));