【发布时间】:2015-10-20 01:23:46
【问题描述】:
我为我的问题寻找了很长时间的解决方案。我有一个自定义 AuthorizeAttribute,它需要依赖于可以访问 DbContext 的“服务”。 遗憾的是,依赖注入在自定义 AuthorizeAttribute 中不起作用,并且始终为空。
我想出了一个(对我而言)可接受的解决方案。现在我想知道我的解决方案是否会导致无法预料的行为?
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());
}
}
这是一个可接受的解决方案吗?我将来会遇到令人讨厌的问题,还是有更好的方法在自定义 AuthorizeAttribute 中使用依赖注入?
【问题讨论】:
标签: c# entity-framework dependency-injection asp.net-mvc-5 authorize-attribute