【问题标题】:Mediator configuration issues. Unable to configure it correctly中介配置问题。无法正确配置
【发布时间】:2021-03-18 06:04:41
【问题描述】:

我刚刚使用中介者模式在 .NET 核心上开展我的项目。我在控制器中创建了一个 get() 方法,该方法将由查询和查询处理程序进一步处理,以提供来自数据库的结果。 以下是我的代码:

UserContoller.cs:

namespace ClaimTrackingSystem.Controllers.UserManager
{
    [Route("api/user")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly ApplicationDBContext _context;
        private readonly IMediator _mediator;

        public UsersController(ApplicationDBContext context, IMediator mediator)
        {
            _context = context;
            _mediator = mediator;
        }

        // GET: api/Users
        [HttpGet]
        public async Task<ActionResult<IEnumerable<User>>> GetAllUser()
        {
            var query = new GetAllUserQuery();
            var result = await _mediator.Send(query);
            return Ok(result);
        }

GetAllUserQuery.cs:

namespace ClaimTrackingSystem.Queries
{
    public class GetAllUserQuery : IRequest<List<UserDTO>>
    {
        public GetAllUserQuery()
        {

        }
    }
}

GetAllUsersQueryHandler.cs:

namespace ClaimTrackingSystem.QueryHandlers
{
    public class GetAllUserQueryHandler : IRequestHandler<GetAllUserQuery, List<UserDTO>>
    {
        private readonly IUserRepository _userRepository;

        public GetAllUserQueryHandler(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }
        public async Task<List<UserDTO>> Handle(GetAllUserQuery request, CancellationToken cancellationToken)
        {
            return (List<UserDTO>)await _userRepository.GetAllUser();
        }
    }
}

Startup.cs:

namespace ClaimTrackingSystem
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureSqlServerContext(Configuration);
            services.ConfigureCors();
            services.ConfigureIISIntegration();
            services.AddControllers();
            services.AddAutoMapper(typeof(Startup));
            services.AddMediatR(typeof(GetAllUserQuery).Assembly);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseCors("CorsPolicy");

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.All
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

程序.cs:

namespace ClaimTrackingSystem
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

repository.cs:

namespace UserService.Data.Repository
{
    public class UserRepository : IUserRepository
    {
        private readonly ApplicationDBContext _context;

        public UserRepository(ApplicationDBContext context)
        {
            _context = context;
        }
        public async Task<IEnumerable<User>> GetAllUser()
        {
            return (IEnumerable<User>)await _context.User.FirstOrDefaultAsync();
        }

        Task<IEnumerable<Domain.Entities.User>> IUserRepository.GetAllUser()
        {
            throw new NotImplementedException();
        }
    }
}

dto.cs:

namespace UserService.Application.DTOs
{
    public class UserDTO
    {
        public Guid ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public Guid Role { get; set; }
        public int Age { get; set; }
    }
}

在 VS 中运行此程序时,我在 main() 方法内的 Program.cs 文件中收到以下错误:

System.AggregateException :  Message=Some services are not able to be constructed Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[ClaimTrackingSystem.Queries.GetAllUserQuery,System.Collections.Generic.List`1[UserService.Application.DTOs.UserDTO]]. Lifetime: Transient ImplementationType: ClaimTrackingSystem.QueryHandlers.GetAllUserQueryHandler': Unable to resolve service for type 'UserService.Domain.Interfaces.IUserRepository' while attempting to activate 'ClaimTrackingSystem.QueryHandlers.GetAllUserQueryHandler'.)
  Source=Microsoft.Extensions.DependencyInjection.

 Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[ClaimTrackingSystem.Queries.GetAllUserQuery,System.Collections.Generic.List`1[UserService.Application.DTOs.UserDTO]] Lifetime: Transient ImplementationType: ClaimTrackingSystem.QueryHandlers.GetAllUserQueryHandler': Unable to resolve service for type 'UserService.Domain.Interfaces.IUserRepository' while attempting to activate 'ClaimTrackingSystem.QueryHandlers.GetAllUserQueryHandler'.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'UserService.Domain.Interfaces.IUserRepository' while attempting to activate 'ClaimTrackingSystem.QueryHandlers.GetAllUserQueryHandler'.

我希望信息是完整的,如果需要任何其他信息,请告诉我。请帮我解决这个问题。 提前谢谢你。

【问题讨论】:

    标签: c# .net-core asp.net-core-mvc asp.net-core-webapi


    【解决方案1】:

    您需要将存储库实现添加到 Startup 类的 ConfigureServices 中的依赖注入容器中,以便它们可以正确注入。

    现在您已经添加了控制器(AddControllers)、IMapperAddAutoMapper)和MediatR 相关类,例如GetAllUserQueryHandlerAddMediatR)。

    但是,GetAllUserQueryHandler 依赖于您尚未添加到容器中的 IUserRepository,因此 DI 库无法创建 GetAllUserQueryHandler 的实例,因为它不知道如何实例化依赖IUserRepository.

    尝试以下方法:

    Startup.cs

    // This method gets called by the runtime.
    // Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.ConfigureSqlServerContext(Configuration);
        services.ConfigureCors();
        services.ConfigureIISIntegration();
        services.AddControllers();
        services.AddAutoMapper(typeof(Startup));
        services.AddMediatR(typeof(GetAllUserQuery).Assembly);
    
        // Add this. Should be Scoped lifetime in this case,
        // but check the docs for getting familiar with the other lifetime alternatives
        services.AddScoped<IUserRepository, UserRepository>();
    }
    

    更多信息请查看the docs

    【讨论】:

    • 抱歉,没用。我们可以在 google meet 上开会吗?如果你有时间,我会得到一些指导。
    • @Prakhar 不抱歉,但这不是一个选择?您是否遇到与原始帖子相同的错误?我很确定你不应该。如果情况发生变化,请更新您的问题
    • 我的 Nuget 包没有响应。系统重新启动后它工作正常。感谢您的帮助。
    • @Prakhar 很高兴它成功了 :) 不客气
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2019-05-09
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多