.NET 6.0依赖注入服务注册异常:无法解析Domain服务
问题分析与解决
报错原因
你的ApiUserRepository构造函数依赖的是具体类Domain,但在DI注册中仅配置了IDomain接口到Domain实现的映射,并未直接注册Domain类型本身。DI容器无法通过IDomain的注册信息来解析Domain具体类的依赖,因此抛出无法解析服务的异常。
解决方案
方案1:遵循依赖倒置原则(推荐)
修改ApiUserRepository的构造函数,依赖IDomain接口而非具体类,这符合仓储模式和依赖注入的设计理念:
public class ApiUserRepository : IApiUserRepository { // 将参数改为IDomain接口 public ApiUserRepository(IDomain domain) { } }
这样DI容器就能通过已注册的IDomain映射,正确解析出Domain实例注入到仓储中。
方案2:直接注册Domain具体类
如果业务场景必须依赖Domain具体类,需要在DI容器中额外注册Domain类型:
// 先注册Domain本身为单例 builder.Services.AddSingleton<Domain>(); // 保持原有IDomain的注册(可选,若仍需通过接口注入) builder.Services.AddSingleton<IDomain>(sp => sp.GetRequiredService<Domain>());
注册后,DI容器就能直接解析Domain类型的依赖,满足ApiUserRepository的构造函数需求。
内容的提问来源于stack exchange,提问作者tRuEsAtM
相关产品推荐
相关产品推荐

