Blazor中ServiceA调用ServiceB启动报错,请求技术帮助
问题解决:Blazor服务间依赖注入失败的修复
你的问题出在ArcNoRuleService的构造函数依赖了具体类ArcNORuleSectionService,而非其对应的接口IArcNORuleSectionService,导致依赖注入容器无法正确解析服务实例。
修复步骤:
1. 修正ArcNoRuleService的构造函数
将构造函数中的ArcNORuleSectionService参数替换为接口IArcNORuleSectionService:
public class ArcNoRuleService : IArcNoRuleService { private readonly IFreeSql _fsql; private readonly IArcNORuleSectionService _arcNORuleSectionService; // 把参数从ArcNORuleSectionService改为IArcNORuleSectionService public ArcNoRuleService(IFreeSql fsql, IArcNORuleSectionService arcNORuleSectionService) { _fsql = fsql; _arcNORuleSectionService = arcNORuleSectionService; } // 接口方法实现... }
2. 确认DI注册顺序(当前已正确)
你的ConfigureServices中已经先注册了被依赖的IArcNORuleSectionService,再注册IArcNoRuleService,这个顺序符合依赖注入的要求,无需调整:
services.AddScoped<IArcNORuleSectionService, ArcNORuleSectionService>(); services.AddScoped<IArcNoRuleService, ArcNoRuleService>();
原因说明
依赖注入的核心原则是依赖抽象而非具体实现:
- 你在DI容器中注册的是「接口-实现类」的映射关系,容器只会根据接口类型查找对应实例
- 直接依赖具体类时,容器无法匹配到已注册的映射,导致启动时无法解析服务,抛出异常
内容的提问来源于stack exchange,提问作者moyi moyi
相关产品推荐
相关产品推荐

