我认为我的问题的细节是非常不同于我有红色的其他类似问题。自定义AuthorizeAttribute Ninject属性注入不起作用(注入的属性有需要注入的子依赖服务)
我知道,当我有自定义的AuthorizeAttribute我不能注入与构造函数的依赖关系。这是因为构造函数将采用参数 - 在我的情况下是权限字符串。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class UserAllCSPermissionBasedAuthFilter : AuthorizeAttribute
{
我依赖于授权服务,这就是为什么我注入使用属性注入。
[Inject]
public IAuthorizationService _authorizationService { get; set; }
问题是这个服务依赖于另一个服务 - 用户服务,它直接与存储库和dbcontext对话。 我已经指定我的数据库上下文生活在请求范围内。 这是一个例外 - “操作无法完成,因为DbContext已被处置。” 当我查看代码时,这是发生在自动化服务调用用户服务,它询问dbcontext的某些数据。 我应该如何避免这种情况发生?
public class AuthorizationService : IAuthorizationService
{
private readonly ICommonRepository _commonRepository;
private readonly IRepositoryBase<UsersInRolesEntity> _repositoryUsersInRoles;
private readonly IRepositoryBase<UserCustomerRolesEntity> _repositoryCurstomerRoleEntities;
private readonly ISqlCustomersRepository _sqlCustomerRepository;
private readonly IRoleService _roleService;
private readonly IUserService _userService;
private readonly IPermissionService _permissionService;
public AuthorizationService(
IRepositoryBase<UsersInRolesEntity> repositoryUsersInRoles,
IRepositoryBase<UserCustomerRolesEntity> repositoryCurstomerRoleEntities,
ICommonRepository commonRepository,
ISqlCustomersRepository sqlCustomerRepository,
IRoleService roleService,
IUserService userService,
IPermissionService permissionService
)
{
我应该在我的情况下使用Ninject条件绑定吗?还是我做错了什么? –
按照[这里](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=98)和[here](http://blog.ploeh)的解释,阻止向您的属性注入依赖项没有自动跳转/ 2014/06/13 /被动属性/)。 – Steven
感谢您的链接,我认为这些链接很有帮助,但我很难消化这些链接。作者说“这种方法的问题是属性实例是由运行时创建的,所以你不能使用正确的依赖注入(DI)模式,如构造器注入(Constructor Injection)。如果一个属性定义了行为(许多Web API属性),编写松散耦合代码最常见的尝试是使用静态服务定位器(一种反模式)。“那么他的解决方案是“定义没有行为的属性”。在他的解决方案中,我看不到如何执行 –