我正在尝试将依赖项注入到自定义中AuthorizeAttribute,如下所示:
AuthorizeAttribute
public class UserCanAccessArea : AuthorizeAttribute { readonly IPermissionService permissionService; public UserCanAccessArea() : this(DependencyResolver.Current.GetService<IPermissionService>()) { } public UserCanAccessArea(IPermissionService permissionService) { this.permissionService = permissionService; } protected override bool AuthorizeCore(HttpContextBase httpContext) { string AreaID = httpContext.Request.RequestContext.RouteData.Values["AreaID"] as string; bool isAuthorized = false; if (base.AuthorizeCore(httpContext)) isAuthorized = permissionService.UserCanAccessArea(AreaID, httpContext.User); return isAuthorized; } }
这是可行的,但似乎可以作为一个单例解决,这意味着我得到了我以前的问题中描述的问题
我想做的是使用属性注入,但是由于我的属性本身无法被Unity解析,因此我无法找到一种方法来配置容器以拦截和解析属性。我尝试了以下方法:
public class UserCanAccessArea : AuthorizeAttribute { public IPermissionService permissionService { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { string AreaID = httpContext.Request.RequestContext.RouteData.Values["AreaID"] as string; bool isAuthorized = false; if (base.AuthorizeCore(httpContext)) isAuthorized = permissionService.UserCanAccessArea(AreaID, httpContext.User); return isAuthorized; } }
容器:
container.RegisterType<UserCanAccessArea>(new InjectionProperty("permissionService"));
但是该属性在运行时始终为null。
有没有人做到这一点,如果有,您有榜样吗?
您应该完全避免将依赖项注入到属性中。本文中对此原因进行了解释:属性中的依赖注入:请勿这样做!。总而言之,本文解释说:
您有两种选择:
AuthorizeCore
使用哪个选项: