Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Dependency Injection with Global Web API Filter Attribute

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?

like image 614
Blake Blackwell Avatar asked Nov 05 '13 16:11

Blake Blackwell


1 Answers

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()));
like image 135
Nicole Calinoiu Avatar answered Oct 19 '22 04:10

Nicole Calinoiu