7

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 Answer 1

16

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()));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this worked, I'd buy you a beer right now, make that 2!
what about filters that I want to apply only to specific actions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.