如何在DI中注册自定义UserManager等-ASP.NET Core 2.1

时间:2018-07-21 01:11:49

标签: c# asp.net-core asp.net-core-2.1

我需要创建自己的类来处理EF Core 2.1中的身份。我有以下内容,但是当要使用控制器的方法时,会出现以下错误

尝试激活“ Sample.API.Models.Identity.Managers.ApplicationUserManager”时,无法解决“ Sample.API.Models.Identity.Stores.ApplicationUserStore”类型的服务。

public void ConfigureServices(IServiceCollection servicesCollection)
{
    servicesCollection.AddDbContext<MyIndentityContext>(currentOptions =>
        currentOptions.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    servicesCollection.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<MyIndentityContext>()
        .AddRoleStore<ApplicationRoleStore>()
        .AddUserStore<ApplicationUserStore>()
        .AddUserManager<ApplicationUserManager>()
        .AddRoleManager<ApplicationRoleManager>()
        .AddSignInManager<ApplicationSignInManager>()
        .AddDefaultTokenProviders();

        servicesCollection.AddTransient<UserManager<ApplicationUser>, ApplicationUserManager>();
        servicesCollection.AddTransient<SignInManager<ApplicationUser>, ApplicationSignInManager>();
        servicesCollection.AddTransient<RoleManager<ApplicationRole>, ApplicationRoleManager>();
        servicesCollection.AddTransient<IUserStore<ApplicationUser>, ApplicationUserStore>();
        servicesCollection.AddTransient<IRoleStore<ApplicationRole>, ApplicationRoleStore>();

        ...

        ...

        ...
}

public class MyIndentityContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
    private readonly IConfiguration _configuration;

    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyIndentityContext(DbContextOptions dbContextOptions, IHttpContextAccessor httpContextAccessor,
        IConfiguration configuration)
        : base(dbContextOptions)
    {
        _configuration = configuration;
        _httpContextAccessor = httpContextAccessor;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.HasDefaultSchema("Sample.API");
    }

}

public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(ApplicationRoleStore roleStore,
        IEnumerable<IRoleValidator<ApplicationRole>> roleValidators, ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors, ILogger<ApplicationRoleManager> logger) : base(roleStore,
        roleValidators,
        keyNormalizer, errors, logger)
    {
    }
}

public class ApplicationSignInManager : SignInManager<ApplicationUser>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IHttpContextAccessor contextAccessor,
        IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor,
        ILogger<ApplicationSignInManager> logger, IAuthenticationSchemeProvider schemes) : base(userManager,
        contextAccessor, claimsFactory, optionsAccessor, logger, schemes)
    {
    }
}

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(ApplicationUserStore userStore, IOptions<IdentityOptions> optionsAccessor,
        IPasswordHasher<ApplicationUser> passwordHasher,
        IEnumerable<IUserValidator<ApplicationUser>> userValidators,
        IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors, IServiceProvider services, ILogger<ApplicationUserManager> logger) :
        base(userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors,
            services, logger)
    {
    }
}

public class ApplicationRoleStore : RoleStore<ApplicationRole, MyIndentityContext>
{
    public ApplicationRoleStore(MyIndentityContext dbContext, IdentityErrorDescriber identityErrorDescriber)
        : base(dbContext, identityErrorDescriber)
    {}
}

public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, MyIndentityContext, string>
{
    public ApplicationUserStore(MyIndentityContext dbContext, IdentityErrorDescriber identityErrorDescriber)
        : base(dbContext, identityErrorDescriber)
    {}

}

public class ApplicationUser : IdentityUser {}

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() { }

    public ApplicationRole(string roleName) : base(roleName) { }

    public ApplicationRole(string roleName, string roleDescription) : base(roleName)
    {
        Description = roleDescription;
    }

}

[Authorize]
[ApiController]
[Route("api/[controller]")]
[EnableCors(CORS.AllowSpecificOrigins)]

public class UserController : BaseController
{
    private readonly ApplicationUserManager _applicationUserManager;

    public UserController(ApplicationUserManager applicationUserManager)
    {
        _applicationUserManager = applicationUserManager;
    }

     // GET: api/User/5
    [HttpGet("{id}")]
    public async Task<UserDTO> Get(int id)
    {

        var currentuser = await _applicationUserManager.FindByNameAsync("NAME");

        return ...;

    }

}

编辑:

完成“ Camilo Terevinto”用户的建议后,我使它起作用,但我还必须更改所有管理器的构造函数。例如,我必须通过 IRoleStore roleStore

更改 ApplicationRoleStore roleStore

1 个答案:

答案 0 :(得分:5)

使用依赖注入时,具有依赖关系的类不要求实现,而是要求合同。

此:

private readonly ApplicationUserManager _applicationUserManager;

public UserController(ApplicationUserManager applicationUserManager)
{
    _applicationUserManager = applicationUserManager;
}

应为:

private readonly UserManager<ApplicationUser> _applicationUserManager;

public UserController(UserManager<ApplicationUser> applicationUserManager)
{
    _applicationUserManager = applicationUserManager;
}

另外,请注意,您不需要任何这些行,这些行已由先前对.AddIdentity及其选项的调用添加。

servicesCollection.AddTransient<UserManager<ApplicationUser>, ApplicationUserManager>();
servicesCollection.AddTransient<SignInManager<ApplicationUser>, ApplicationSignInManager>();
servicesCollection.AddTransient<RoleManager<ApplicationRole>, ApplicationRoleManager>();
servicesCollection.AddTransient<IUserStore<ApplicationUser>, ApplicationUserStore>();
servicesCollection.AddTransient<IRoleStore<ApplicationRole>, ApplicationRoleStore>();