Injecting dependencies into custom Web API action filter attribute with Autofac

后端 未结 4 460
甜味超标
甜味超标 2021-02-05 06:15

I\'m trying to resolve the dependencies of my custom AuthorizeAttribute which I use to decorate my API controllers in an MVC4 app. Problem is that I keep getting a

相关标签:
4条回答
  • 2021-02-05 06:25

    You should configure property injection for your attribute

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        public IAuthenticationSvc AuthenticationSvc { get; set; }
    }
    

    and the builder

    builder.RegisterType<MyAuthorizeAttribute>().PropertiesAutowired();
    
    0 讨论(0)
  • 2021-02-05 06:25

    I think Autofac's documentation offers much simpler solution for WebApi action filters.

    public interface ServiceCallActionFilterAttribute : ActionFilterAttribute
    {
      public override void OnActionExecuting(HttpActionContext actionContext)
      {
        // Get the request lifetime scope so you can resolve services.
        var requestScope = actionContext.Request.GetDependencyScope();
    
        // Resolve the service you want to use.
        var service = requestScope.GetService(typeof(IMyService)) as IMyService;
    
        // Do the rest of the work in the filter.
        service.DoWork();
      }
    }
    

    It is not "pure DI" as it is using service locator, but it is simple and works with the request scope. You don't need to worry about registering specific action filter for each WebApi controller.

    Source: http://autofac.readthedocs.io/en/latest/integration/webapi.html#provide-filters-via-dependency-injection

    0 讨论(0)
  • 2021-02-05 06:31

    In addition to @Toan Nguyen's answer, if you have this...

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        public IAuthenticationSvc AuthenticationSvc { get; set; }
    }
    

    ... it seems you also need (or may need) the first line below:

    builder.RegisterFilterProvider();
    builder.RegisterType<MyAuthorizeAttribute>().PropertiesAutowired();
    

    Reference: http://itprojectpool.blogspot.com.au/2014/03/autofac-di-on-action-filters.html

    0 讨论(0)
  • 2021-02-05 06:34

    In addition to configuring property injection, as outlined in other answers, you can also explicitly resolve dependencies in the OnActivating callback.

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        private IAuthenticationSvc _authenticationSvc;
        public void SetAuthenticationSvc(IAuthenticationSvc svc)
        {
           this._authenticationSvc = svc;
        }
    }
    

    And then register the type:

    builder.RegisterType<MyAuthorizeAttribute>()
        .OnActivating(_ => _.Instance.SetAuthenticationSvc(_.Context.Resolve<IAuthenticationSvc>()));
    

    Note: You can do the same with a property instead of a method. I chose to use a method here only to illustrate that this solution was not dependent on PropertiesAutowired.

    0 讨论(0)
提交回复
热议问题