我正在根据这个 使用 MediatR 执行命令的干净架构示例构建 ASP.Net Core 应用程序。而且我想在我的应用程序中使用 ASP.Net Core Identity,所以在我的 CreateUserCommandHandler 中我想使用 UserManager 添加新用户,但是当我将 UserManager 添加到命令承包商 MediatR 时无法创建处理程序并因以下异常而失败:
System.InvalidOperationException: Error constructing handler for request of type MediatR.IRequestHandler`2[GoGYM.Application.Identity.Commands.CreateUser.CreateUserCommand,MediatR.Unit]. Register your handlers with the container. See the samples in GitHub for examples. ---> System.InvalidOperationException: Unable to resolve service for type 'GoGYM.Persistence.GoGYMDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[GoGYM.Domain.Entities.ApplicationUser,GoGYM.Domain.Entities.ApplicationRole,GoGYM.Persistence.GoGYMDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim`1[System.String],Microsoft.AspNetCore.Identity.IdentityUserRole`1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin`1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken`1[System.String],Microsoft.AspNetCore.Identity.IdentityRoleClaim`1[System.String]]'.
在配置服务中,我像这样注册我的 DBContext 和 MediatR:
// Add AutoMapper
services.AddAutoMapper(new Assembly[] { typeof(AutoMapperProfile).GetTypeInfo().Assembly });
// Add MediatR
services.AddMediatR(typeof(GetUsersListQueryHandler).GetTypeInfo().Assembly);
// Add DbContext using SQL Server Provider
services.AddDbContext<IGoGYMDbContext, GoGYMDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("NorthwindDatabase")));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<GoGYMDbContext>();
services.AddMvc();
....
这是我的命令处理程序代码:
public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, Unit>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IGoGYMDbContext _context;
public CreateUserCommandHandler(IGoGYMDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
public Task<Unit> Handle(CreateUserCommand request, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
还有我的控制器
[HttpPost]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesDefaultResponseType]
public async Task<IActionResult> Create(string values)
{
await Mediator.Send(new CreateUserCommand(values));
return NoContent();
}
我已经尝试了很多东西,但没有任何效果,只有当我从命令处理程序中删除 UserManager 时,它才会被执行。