Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't inject on System.Web.Http.Filters.ActionFilterAttribute using Unity bootstrapper for ASP.NET Web API nuget package

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.

like image 985
Michael Szabo Avatar asked Oct 02 '13 05:10

Michael Szabo


1 Answers

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.

like image 122
Randy supports Monica Avatar answered Nov 14 '22 10:11

Randy supports Monica