How do I resolve Dependency Injection in MVC Filter attributes

前端 未结 4 571
灰色年华
灰色年华 2021-02-07 15:36

I have a custom attribute class derived from AuthorizationAttribute, which performs custom security on controller actions. The OnAuthorizationCore method depends on various othe

4条回答
  •  自闭症患者
    2021-02-07 16:10

    I would seem that the easiest way to achieve this is to bite the bullet and accept a dependency on autofac itself. While a dependency on the IoC is in itself an anti-pattern, it's somewhat more pallatable. You can implement a property as follows:

    public class UserAuthorizeAttribute : AuthorizeAttribute
    {            
        public IUserRepository CurrentUserService
        {
            get
            {
                var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
                var cp = cpa.ContainerProvider;
                return cp.RequestLifetime.Resolve();
            }
        }
    }
         ...
    

提交回复
热议问题