Asp.net MVC5 - Dependency Injection and Authorized Attribute

I have been looking for a solution to my problem for a long time. I have a custom attribute, AuthorizeAttribute, which requires a dependency on a service that has access to DbContext. Unfortunately, dependency injection did not work in the custom attribute AuthorizeAttribute and was always null.

I came up with an acceptable solution (for me). Now I want to know if my decision can cause unexpected behavior?

Global.asax.cs

CustomAuthorizeAttribute.AuthorizeServiceFactory = () => unityContainer.Resolve<AuthorizeService>(); 

CustomAuthorizeAttribute.cs

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class CustomAuthorizeAttribute : AuthorizeAttribute { public static Func<AuthorizeService> AuthorizeServiceFactory { get; set; } public Privilege Privilege { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { bool authorized = base.AuthorizeCore(httpContext); if (!authorized) { return false; } return AuthorizeServiceFactory().AuthorizeCore(httpContext, Privilege); } } 

AuthorizeService.cs

 public class AuthorizeService { [Dependency] public UserService UserService { private get; set; } public bool AuthorizeCore(HttpContextBase httpContext, Privilege privilege) { ApplicationUser user = UserService.FindByName(httpContext.User.Identity.Name); return UserService.UserHasPrivilege(user.Id, privilege.ToString()); } } 

Is this an acceptable solution? Will I encounter unpleasant problems in the future, or may be the best way to use dependency injection in a custom attribute of AuthorizeAttribute?

+7
c # dependency-injection entity-framework asp.net-mvc-5
source share
1 answer

I have a custom attribute, AuthorizeAttribute, which requires a dependency on a "Service" that has access to DbContext. Unfortunately, the Injection dependency did not work in the custom AuthorizeAttribute and was always zero.

Implementing IControllerFactory in the System.Web.Mvc creates instances of your controllers for web requests. The Factory controller uses System.Web.Mvc.DependencyResolver to resolve dependencies in each controller.

However ActionFilters / Attributes in

+8
source share

All Articles