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?
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With