我花了很长时间寻找解决我的问题的方法。我有一个自定义的 AuthorizeAttribute,它需要依赖于可以访问 DbContext 的“服务”。
遗憾的是,依赖注入在自定义 AuthorizeAttribute 中不起作用,并且始终为 null。
我想出了一个(对我来说)可以接受的解决方案。现在我想知道我的解决方案是否会导致不可预见的行为?
全局.asax.cs
CustomAuthorizeAttribute.AuthorizeServiceFactory = () => unityContainer.Resolve<AuthorizeService>();
自定义AuthorizeAttribute.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);
}
}
授权服务.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 中使用依赖注入?
我有一个自定义的 AuthorizeAttribute 需要依赖于
有权访问 DbContext 的“服务”。可悲的是依赖
注入在自定义 AuthorizeAttribute 中不起作用,并且始终
无效的。
一个实现IControllerFactory
in the System.Web.Mvc
命名空间创建您的实例控制器用于网络请求。控制器工厂使用System.Web.Mvc.DependencyResolver
解决每个控制器中的依赖关系。
然而,动作过滤器/属性 in the MVC管道 http://www.dotnet-tricks.com/Tutorial/mvc/LYHK270114-Detailed-ASP.NET-MVC-Pipeline.html不是从控制器工厂创建的,因此无法使用以下命令解决依赖关系System.Web.Mvc.DependencyResolver
。这就是为什么你总是依赖null
.
Now, System.Web.Mvc.DependencyResolver
is public
and static
这样您就可以自己访问它。
public class AuthorizeService : AuthorizeAttribute
{
private UserService UserService
{
get
{
return DependencyResolver.Current.GetService<UserService>();
}
}
public bool AuthorizeCore(HttpContextBase httpContext, Privilege privilege)
{
ApplicationUser user = UserService.FindByName(httpContext.User.Identity.Name);
return UserService.UserHasPrivilege(user.Id, privilege.ToString());
}
}
假设你的UserService
依赖范围为网络请求,即它的寿命是每个网络请求一个并与生命周期相关联HttpContext
Web 请求的这不会构造一个新的UserService
如果之前或之后已解决 如果这是第一次UserService
已解决给定的 Web 请求。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)