gpt4 book ai didi

c# - 无法解析 'MediatR.IMediator'类型的服务

转载 作者:行者123 更新时间:2023-12-03 15:42:29 26 4
gpt4 key购买 nike

我尝试使用CQRS制作.NET Core API,但由于MediatR错误而无法构建它:

System.AggregateException:'某些服务无法构造(验证服务描述符'ServiceType:Core.Infrastructure.Domain.Queries.IQueryBus的生存期:范围实现类型: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();
});
}
}

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

感谢帮助

最佳答案

您尚未在启动时注册Mediatr本身,因此DI容器无法解决它,如错误所示。

您可以从NuGet添加MediatR DI扩展,然后在启动时注册MediatR:

To use, with an IServiceCollection instance:

services.AddMediatR(typeof(MyHandler));

or with an assembly:

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



https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection

https://www.nuget.org/packages/MediatR.Extensions.Microsoft.DependencyInjection/

关于c# - 无法解析 'MediatR.IMediator'类型的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61543605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com