How to use dependency injection in ActionFilter We

2019-07-24 13:35发布

问题:

I am trying to get work with dependency injection into the action filter, but it seems not working

I've registered the type in UnityConfig

    public static void RegisterComponents(IUnityContainer container)
    {
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        container.RegisterType<Domain.Contracts.IUserServices, Domain.UserServices>(new ContainerControlledLifetimeManager());
        ...
    }

The code is being called successfully, however, the instantiated object (IUserServices) is null.

public class ValidationActionFilter : ActionFilterAttribute
{
    [Dependency]
    public IUserServices userServices { get; set; }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var isValidUser = userServices.IsAValidUserForCompany("MyCompany", 123);
        ....
     }
}

I have tried to use following link solution, but this does not seem working for me because it IUnityContainer is null for me always

Solution

First, I have created an IFilterProvider

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 registered the IFilterProvider in global.asax

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        UnityConfig.RegisterComponents(UnityConfig.GetConfiguredContainer());


        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);
    }
}