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?
c # dependency-injection entity-framework asp.net-mvc-5
Shamshiel
source share