我正在开发3层体系结构应用程序,因此我将UserManager和RoleManager添加到数据访问层的UnitOfWork中。但是,当我尝试创建UserManager和RoleManager类的对象时,出现此错误:
There is no argument given that corresponds to the required formal parameter 'optionsAccessor'
of 'UserManager<IdentityUser>.UserManager(IUserStore<IdentityUser>, IOptions<IdentityOptions>,
IPasswordHasher<IdentityUser>, IEnumerable<IUserValidator<IdentityUser>>,
IEnumerable<IPasswordValidator<IdentityUser>>, ILookupNormalizer, IdentityErrorDescriber,
IServiceProvider, ILogger<UserManager<IdentityUser>>)'
There is no argument given that corresponds to the required formal parameter 'roleValidators'
of 'RoleManager<IdentityRole>.RoleManager(IRoleStore<IdentityRole>, IEnumerable<IRoleValidator<IdentityRole>>,
ILookupNormalizer, IdentityErrorDescriber, ILogger<RoleManager<IdentityRole>>)'
我的UnitOfWork类的一部分
public class IdentityUnitOfWork : IUnitOfWork
{
private UserManager<IdentityUser> _userManager;
private RoleManager<IdentityRole> _roleManager;
private ApplicationContext _context;
public IdentityUnitOfWork(ApplicationContext context)
{
_userManager = new UserManager<IdentityUser>(context);// error 1
_roleManager = new RoleManager<IdentityRole>(context);// error 2
_context = context;
}
}
更新
[当我尝试创建自己的RoleManager
和UserManager
类时,出现相同的错误。
我的ApplicationRole
类
public class ApplicationRole : IdentityRole
{
}
我的ApplicationRoleManager
类
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
public ApplicationRoleManager(RoleStore<ApplicationRole> store)
: base(store)// error in a here (in a base)
{
}
}
您已将身份服务添加到IoC容器。因此,您可以像这样使用依赖注入到UnitOfWork的构造函数中:
public class IdentityUnitOfWork : IUnitOfWork
{
private UserManager<IdentityUser> _userManager;
private RoleManager<IdentityRole> _roleManager;
private ApplicationContext _context;
public IdentityUnitOfWork(ApplicationContext context,
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
_context = context;
}
}
代替直接将上下文传递给用户和角色管理器,您需要创建用户和角色存储,并像这样将上下文传递给用户和角色存储
public class IdentityUnitOfWork : IUnitOfWork
{
private UserManager<IdentityUser> _userManager;
private RoleManager<IdentityRole> _roleManager;
private DbContext _context;
public IdentityUnitOfWork(DbContext context)
{
_userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(context));
_roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
_context = context;
}
}
错误也建议使用用户存储和角色存储