无法解析 "MediatR.IMediator "类型的服务。

问题描述 投票:0回答:1

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

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Core.Infrastructure.Domain.Query.IQueryBus Lifetime.Scoped ImplementationType: IQueryBus Lifetime: 服务类型:Core.Infrastructure.Domain.Query.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();
            });
        }
    }

QueryBus: IQueryBus:

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
1个回答
0
投票

你在启动时没有注册Mediatr本身,所以DI容器未能解决它,正如错误所暗示的那样。

你可以从NuGet中添加MediatR DI扩展,然后在启动时注册MediatR。

使用IServiceCollection实例:

services.AddMediatR(typeof(MyHandler));

或与一个汇编一起使用。

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

https:/github.comjbogardMediatR.Extensions.Microsoft.DependencyInjection。

https:/www.nuget.orgpackagesMediatR.Extensions.Microsoft.DependencyInjection

© www.soinside.com 2019 - 2024. All rights reserved.