调解器配置问题.无法正确配置它



我只是使用中介模式在.NET core上处理我的项目。我在控制器中创建了一个 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();
}
}
}

启动.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>();
});
}
}

存储库.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中运行此程序时,我在方法中的程序.cs文件中收到以下错误main()

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'.

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

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

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

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

请尝试以下操作:

启动.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>();
}

有关更多信息,请查看文档

最新更新