首页 > 解决方案 > 使用 Aspnet Core Identiy 实现 CQRS 时如何注册处理程序

问题描述

我正在尝试使用 CQRS 注册我的用户。

我正在注册 MediatR:

services.AddMediatR(typeof(MyCommand).GetTypeInfo().Assembly);


public class Handler : IRequestHandler<RegisterCommand, object>
        {
            private readonly MyDbContext _context;
            private readonly IMediator _mediator;
            private readonly UserManager<User> _userManager;

            public Handler(IYawaMVPDbContext context, IMediator mediator, UserManager<User> userManager)
            {
                _context = context;
                _mediator = mediator;
                _userManager = userManager;
            }
}

我收到以下异常:

InvalidOperationException:尝试激活“Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore 6[MyCore.Domain.Entities.User,MyCore.MyApp.Persistence.MyDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String]]”时无法解析“MyDbContext”类型的服务。Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(类型 serviceType,类型 implementationType,CallSiteChain callSiteChain,ParameterInfo[] 参数,bool throwIfCallSiteNotFound)

InvalidOperationException:为 MediatR.IRequestHandler`2[MyCore.MyApp.Application.Users.Commands.Register.RegisterCommand,System.Object] 类型的请求构造处理程序时出错。

向容器注册您的处理程序。有关示例,请参阅 GitHub 中的示例。

任何帮助表示赞赏。

标签: asp.net-coreasp.net-identitymediatr

解决方案


我认为以下代码没有问题

services.AddMediatR(typeof(MyCommand).GetTypeInfo().Assembly);

处理所有 MediatR IRequest 和 IRequestHandlers。

但是您创建了一个 IYawaMVPDbContext 接口及其无法处理的实现类MediatR.Extensions.Microsoft.DependencyInjection

DBContext 在应用程序启动期间注册依赖注入,以便它们可以自动提供给使用服务的组件 - 手动注册这个

services.AddDbContext<IYawaMVPDbContext, DbContextImplementation>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));


推荐阅读