Unity Dependency Injection with Global Web API Filter Attribute

南笙酒味 提交于 2019-12-04 11:44:17

问题


Referencing this CodePlex unity article I was able to get filter attribute working with a WebAPI controller as follows:

[MyFilterAttribute]
public class TestController : ApiController
{}

However, if I want to apply my filter attribute across all actions with a GlobalConfiguration it gets stripped of the injected dependency:

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

Is there a better place to add the Global Configuration?


回答1:


The problem is occurring because you are adding a newed MyFilterAttribute to the filters collection (i.e.: GlobalConfiguration.Configuration.Filters.Add(**new MyFilterAttribute()**)) as opposed to an instance resolved through Unity. Since Unity does not participate in creation of the instance, it has no trigger for injecting the dependency. This should be addressable by simply resolving the instance through Unity. e.g.:

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


来源:https://stackoverflow.com/questions/19794438/unity-dependency-injection-with-global-web-api-filter-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!