Search code examples
c#asp.net-coreasp.net-identityidentitydata-access-layer

Can not create objects of Identity classes (UserManager and RoleManager)


I am developing a 3 tier architecture app, so I add UserManager and RoleManager to my UnitOfWork at Data Access Layer. But when I try to create objects of UserManager and RoleManager classes I get this errors:

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>>)'

Part of my UnitOfWork class

    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;
        }
    }

UPDATE

When I try to create my own RoleManager and UserManager classes, I get the same error.

My ApplicationRole class

    public class ApplicationRole : IdentityRole
    {

    }

My ApplicationRoleManager class

    public class ApplicationRoleManager : RoleManager<ApplicationRole>
    {
        public ApplicationRoleManager(RoleStore<ApplicationRole> store)
                    : base(store)// error in a here (in a base)
        {

        }
    }

Solution

  • You have added identity service to IoC container. So you can use dependency injection into UnitOfWork's constructor like this:

    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;
        }
    }