ASP.NET Core 7 Web API中Program.cs注册双服务遇循环依赖错误
解决ASP.NET Core 7中ICustomerCommandRepository的循环依赖问题
从错误信息可以明确看出,CustomerCommandRepository的构造函数中注入了ICustomerCommandRepository本身,导致了自循环依赖:
ModiranKhodro.Core.Contracts.Customers.Commands.ICustomerCommandRepository(CustomerCommandRepository) -> ICustomerCommandRepository
解决步骤:
检查并修正CustomerCommandRepository的构造函数
打开CustomerCommandRepository的实现代码,找到构造函数,移除对ICustomerCommandRepository的注入。正常情况下,仓储类应该依赖数据库上下文(比如DbContext)、查询仓储(ICustomerQueryRepository)或其他基础服务,而非自身的接口。错误示例(导致循环):
public class CustomerCommandRepository : ICustomerCommandRepository { private readonly ICustomerCommandRepository _customerCommandRepo; // 错误:注入了自身接口 public CustomerCommandRepository(ICustomerCommandRepository customerCommandRepo) { _customerCommandRepo = customerCommandRepo; } }修正后的示例(注入正确依赖):
public class CustomerCommandRepository : ICustomerCommandRepository { private readonly AppDbContext _dbContext; private readonly ICustomerQueryRepository _customerQueryRepo; public CustomerCommandRepository(AppDbContext dbContext, ICustomerQueryRepository customerQueryRepo) { _dbContext = dbContext; _customerQueryRepo = customerQueryRepo; } // 实现ICustomerCommandRepository的方法 }重新验证服务注册
你的现有注册代码本身无问题:builder.Services.AddScoped<ICustomerQueryRepository, CustomerQueryRepository>(); builder.Services.AddScoped<ICustomerCommandRepository, CustomerCommandRepository>();只要修复
CustomerCommandRepository的构造函数,该注册逻辑就能正常运行,MediatR的Handler依赖问题也会随之解决。极端情况的临时方案(不推荐)
如果因特殊设计需求必须保留类似依赖(非常罕见),可通过IServiceProvider延迟获取服务规避循环:public class CustomerCommandRepository : ICustomerCommandRepository { private readonly IServiceProvider _serviceProvider; private ICustomerCommandRepository? _customerCommandRepo; public CustomerCommandRepository(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } private ICustomerCommandRepository CustomerCommandRepo => _customerCommandRepo ??= _serviceProvider.GetRequiredService<ICustomerCommandRepository>(); // 使用CustomerCommandRepo的方法 }注意:这种方式会掩盖设计缺陷,优先推荐修复构造函数的依赖逻辑。
内容的提问来源于stack exchange,提问作者Dariush Marandi
相关产品推荐
相关产品推荐

