asp.net MVC5 - Dependency Injection and AuthorizeAttribute

后端 未结 3 1799
旧时难觅i
旧时难觅i 2021-02-13 00:59

I searched a long time for a solution for my problem. I have a custom AuthorizeAttribute that needs a Dependency to a \"Service\" that has access to a DbContext. Sadly the Depe

3条回答
  •  一整个雨季
    2021-02-13 01:34

    I have a custom AuthorizeAttribute that needs a Dependency to a "Service" that has access to a DbContext. Sadly the Dependency Injection did not work in the custom AuthorizeAttribute and was always null.

    An implementation of IControllerFactory in the System.Web.Mvc namespace creates instances your Controllers for web requests. The Controller Factory uses System.Web.Mvc.DependencyResolver to resolve dependencies in each controller.

    However, ActionFilters/Attributes in the MVC pipeline are not created from the Controller Factory so dependencies are not resolved using System.Web.Mvc.DependencyResolver. This is why your dependency was always null.

    Now, System.Web.Mvc.DependencyResolver is public and static so you can access it yourself.

        public class AuthorizeService : AuthorizeAttribute
        {
            private UserService UserService
            {
                get
                {
                    return DependencyResolver.Current.GetService();
                }
            }
    
            public bool AuthorizeCore(HttpContextBase httpContext, Privilege privilege)
            {
                ApplicationUser user = UserService.FindByName(httpContext.User.Identity.Name);
                return UserService.UserHasPrivilege(user.Id, privilege.ToString());
            }
        }
    

    Assuming your UserServicehas a dependency scope of WebRequest, i.e. its lifetime is One Per web request and tied to the lifetime of HttpContext of a web request this will not construct a new UserService if one has been resolved previously or after if this is the first time UserService has been resolved for the given web request.

提交回复
热议问题