.NET 8依赖注入报错:部分服务无法构造的原因与解决
在.NET 8项目启动时触发System.AggregateException,核心错误提示:
Implementation type 'CarRepository' can't be converted to service type 'BookACar.Application.Interfaces.CarInterfaces.ICarRepository'
错误详情
System.AggregateException
HResult=0x80131500
Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: BookACar.Application.Interfaces.CarInterfaces.ICarRepository Lifetime: Scoped ImplementationType: CarRepository': Implementation type 'CarRepository' can't be converted to service type 'BookACar.Application.Interfaces.CarInterfaces.ICarRepository') (Error while validating the service descriptor 'ServiceType: BookACar.Application.Features.CQRS.Handlers.CarHandlres.GetCarWithBrandQueryHandler Lifetime: Scoped ImplementationType: BookACar.Application.Features.CQRS.Handlers.CarHandlres.GetCarWithBrandQueryHandler': Implementation type 'CarRepository' can't be converted to service type 'BookACar.Application.Interfaces.CarInterfaces.ICarRepository')
Source=Microsoft.Extensions.DependencyInjectionStackTrace:
at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()
at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
at Program.$(String[] args) in C:\Projects\CarBook\Presentation\BookACar.WebApi\Program.cs:line 51 This exception was originally thrown at this call stack:
[External Code]Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: BookACar.Application.Interfaces.CarInterfaces.ICarRepository Lifetime: Scoped ImplementationType: CarRepository': Implementation type 'CarRepository' can't be converted to service type 'BookACar.Application.Interfaces.CarInterfaces.ICarRepository'Inner Exception 2:
ArgumentException: Implementation type 'CarRepository' can't be converted to service type 'BookACar.Application.Interfaces.CarInterfaces.ICarRepository'
相关代码
ICarRepository接口
namespace BookACar.Application.Interfaces.CarInterfaces { public interface ICarRepository { List<Car> GetCarsListWithBrand(); } }
CarRepository实现类
namespace BookACar.Persistence.Repositories.CarRepositories { public class CarRepository : ICarRepository { private readonly CarBookContext _context; public CarRepository(CarBookContext context) { _context = context; } public List<Car> GetCarsListWithBrand() { var values = _context.Cars.Include(x => x.Brand).ToList(); return values; } } }
Program.cs服务注册
using BookACar.Application.Features.CQRS.Handlers.AboutHandlers; using BookACar.Application.Features.CQRS.Handlers.BannerHandlres; using BookACar.Application.Features.CQRS.Handlers.BrandHandlers; using BookACar.Application.Features.CQRS.Handlers.CarHandlres; using BookACar.Application.Interfaces; using BookACar.Application.Interfaces.CarInterfaces; using BookACar.Persistence.Repositories; using BookACar.Persistence.Repositories.CarRepositories; using CarBook.Persistence.CarBookContext; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddScoped<CarBookContext>(); builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); builder.Services.AddScoped(typeof(ICarRepository), typeof(CarRepository)); builder.Services.AddScoped<GetCarQueryHandler>(); builder.Services.AddScoped<GetCarByIdQueryHandler>(); builder.Services.AddScoped<CreateCarCommandHandler>(); builder.Services.AddScoped<UpdateCarCommandHandler>(); builder.Services.AddScoped<RemoveCarCommandHandler>(); builder.Services.AddScoped<GetCarWithBrandQueryHandler>(); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
问题原因
- 命名空间冲突:项目中可能存在另一个同名的
ICarRepository接口或CarRepository类,导致DI容器无法正确匹配实现与接口。 - 程序集引用异常:
BookACar.Persistence程序集未被WebApi项目正确引用,或存在版本不一致,导致编译后类型无法识别。 - 编译缓存问题:项目的
bin/obj文件夹存在旧编译文件,导致类型继承关系未正确更新。
修复步骤
- 校验命名空间与引用:确认
CarRepository类中引用的ICarRepository来自BookACar.Application.Interfaces.CarInterfaces命名空间,同时WebApi项目已正确引用BookACar.Persistence程序集。 - 清理重建解决方案:删除所有项目的
bin和obj文件夹,执行dotnet clean和dotnet build命令,清除编译缓存。 - 显式指定完整命名空间注册服务:修改Program.cs中的服务注册代码,使用完整命名空间确保类型匹配:
builder.Services.AddScoped<BookACar.Application.Interfaces.CarInterfaces.ICarRepository, BookACar.Persistence.Repositories.CarRepositories.CarRepository>(); - 检查项目依赖链:确认
BookACar.Persistence项目已添加对BookACar.Application项目的引用,保证接口能被正确继承。
内容的提问来源于stack exchange,提问作者Soner

