Injecting dependencies into custom Web API action filter attribute with Autofac

后端 未结 4 459
甜味超标
甜味超标 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: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()
        .OnActivating(_ => _.Instance.SetAuthenticationSvc(_.Context.Resolve()));
    

    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.

提交回复
热议问题