【发布时间】:2020-08-16 00:13:13
【问题描述】:
我尝试使用 CQRS 制作 .NET Core API,但由于 MediatR 错误,我无法构建它:
System.AggregateException:'某些服务无法构建(验证服务描述符时出错'ServiceType:Core.Infrastructure.Domain.Queries.IQueryBus Lifetime:Scoped ImplementationType:Core.Infrastructure.Bus.QueryBus':无法在尝试激活“Core.Infrastructure.Bus.QueryBus”时解析“MediatR.IMediator”类型的服务。)”
我已经为我的 QueryBus 等添加了“AddScope”。这是我的代码(适用于 AWS 的应用程序):
public class Startup
{
public const string AppS3BucketKey = "AppS3Bucket";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public static IConfiguration Configuration { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAWSService<Amazon.S3.IAmazonS3>();
services.AddScoped<IQueryBus, QueryBus>();
services.AddScoped<IWarehouseRepository, WarehouseRepository>();
services.AddScoped<IRequestHandler<GetAllWarehouseDepartmentsQuery, IEnumerable<WarehouseDepartmentDto>>, WarehouseQueryHandler>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
查询总线:
using System.Threading.Tasks;
using Core.Infrastructure.Domain.Queries;
using MediatR;
namespace Core.Infrastructure.Bus
{
public class QueryBus : IQueryBus
{
private readonly IMediator _mediator;
public QueryBus(IMediator mediator)
{
_mediator = mediator;
}
public Task<TResponse> Send<TQuery, TResponse>(TQuery query) where TQuery : IQuery<TResponse>
{
return _mediator.Send(query);
}
}
}
IQueryBus:
using System.Threading.Tasks;
namespace Core.Infrastructure.Domain.Queries
{
public interface IQueryBus
{
Task<TResponse> Send<TQuery, TResponse>(TQuery query) where TQuery : IQuery<TResponse>;
}
}
感谢您的帮助
【问题讨论】:
标签: c# asp.net .net cqrs mediatr