C# 中介配置问题。无法正确配置它

C# 中介配置问题。无法正确配置它,c#,.net-core,asp.net-core-mvc,asp.net-core-webapi,C#,.net Core,Asp.net Core Mvc,Asp.net Core Webapi,我正在使用中介模式在.NETCore上完成我的项目。我在控制器中创建了一个get()方法,该方法将由查询和查询处理程序进一步处理,以提供来自数据库的结果。 以下是我的代码: UserContoller.cs: namespace ClaimTrackingSystem.Controllers.UserManager { [Route("api/user")] [ApiController] public class UsersController :

我正在使用中介模式在.NETCore上完成我的项目。我在控制器中创建了一个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);
        }
Program.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>();
                });
    }
}
在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'.
我希望信息是完整的,如果需要任何其他信息,请告诉我。请帮我解决这个问题。
提前感谢。

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

现在,您已经添加了控制器(使用
AddControllers
)、
IMapper
(使用
AddAutoMapper
)和
MediatR
相关类,例如
GetAllUserQueryHandler
(使用
AddMediatR

但是,
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>();
}
//此方法由运行时调用。
//使用此方法向容器中添加服务。
public void配置服务(IServiceCollection服务)
{
services.ConfigureSqlServerContext(配置);
services.ConfigureCors();
services.ConfigureIISIntegration();
services.AddControllers();
AddAutoMapper(类型(启动));
AddMediatR(typeof(GetAllUserQuery).Assembly);
//添加此。在这种情况下,应为作用域生存期,
//但是检查文档是否熟悉其他的生命周期替代方案
services.addScope();
}

有关更多信息,请查看

@prakar它解决了您的问题吗?对不起,没用。我们可以开一个关于google meet的会议吗?如果你有时间,我会在这方面得到一些指导。@Prakar不抱歉,但这不是我的Nuget软件包没有响应的选项。系统重启后,它工作正常。谢谢你的帮助。@Prakar很高兴它成功了:)不客气
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>();
                });
    }
}
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();
        }
    }
}
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; }
    }
}
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'.
// 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>();
}