I can't get dependency injection working with a custom ActionFilterAttribute class using the Unity bootstrapper for ASP.NET Web API nuget package.
I've registered the type in UnityConfig and I'm using it elsewhere (using constructor injection there though) and it works fine.
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<ISettingService, SettingService>();
...
}
The code is being called successfully, however the instantiated object (settingService) is null.
public class APIKeyValidationAttribute : ActionFilterAttribute
{
[Dependency]
public ISettingService settingService { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
...
if (settingService == null)
{
throw new Exception("settingService is null");
}
...
}
What do I need to do to get this working? I've been searching for a long time and can only find examples for MVC or for Web API with different dependency injectors.
First create an IFilterProvider
that will perform a BuildUp and inject the dependencies:
public class UnityActionFilterProvider
: ActionDescriptorFilterProvider, IFilterProvider
{
private readonly IUnityContainer container;
public UnityActionFilterProvider(IUnityContainer container)
{
this.container = container;
}
public new IEnumerable<FilterInfo> GetFilters(
HttpConfiguration configuration,
HttpActionDescriptor actionDescriptor)
{
var filters = base.GetFilters(configuration, actionDescriptor);
foreach (var filter in filters)
{
container.BuildUp(filter.Instance.GetType(), filter.Instance);
}
return filters;
}
}
Then register the IFilterProvider:
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);
}
I put this method and invoked it in the UnityWebApiActivator
class.
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