You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AddKeyedScoped注册服务及实现时出现循环依赖错误排查

问题分析与解决

代码展示

接口定义

public interface IService
{
  public Task<string> GetString();
}

DAL类实现

public class SampleDAL : IService
{
  public async Task<string> GetString()
  { 
    //do something 
  }
}

BL类实现

public class SampleBl([FromKeyedServices("SampleBl")]IService service) : IService
{
  public Task<string> GetString()
  {
   var something = service.GetString();
   return something;
  }
}

控制器代码

[Route("[controller]")]
[ApiController]
public class SampleController([FromKeyedServices("SampleBl")] IService serviceBl) : Controller
{
  [HttpGet("GetSomeString")]
  public async Task<string> GetString()
  {
    var somethingout = serviceBl.GetString();
    return somethingout;
  }
}

服务注册代码

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKeyedScoped<IService, SampleDal>("SampleDal");
builder.Services.AddKeyedScoped<IService, SampleBl>("SampleBl");

错误信息

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Lifetime: Scoped ServiceKey: KeyedImplementationType: ': A circular dependency was detected for the service of type ''.

错误原因

SampleBl类构造函数使用[FromKeyedServices("SampleBl")]注入IService,这会让DI容器尝试注入SampleBl自身,形成循环依赖:SampleBl依赖SampleBl,容器无法解析这种引用关系。

解决方案

SampleBl作为业务逻辑层,应该依赖DAL层的实现,也就是Key为"SampleDal"的IService,修改构造函数的注入标记即可:

修改后的SampleBl代码:

public class SampleBl([FromKeyedServices("SampleDal")]IService service) : IService
{
  public async Task<string> GetString()
  {
   var something = await service.GetString();
   return something;
  }
}

另外注意:service.GetString()是异步方法,需要加上await关键字,否则会返回未完成的Task,可能引发后续执行异常。

内容的提问来源于stack exchange,提问作者user876120

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:56:02