ASP.NET MVC控制器注册位置咨询:添加依赖后实例化失败报错
问题解决思路
报错核心原因
这个错误本质是Web API的依赖注入(DI)容器找不到你新增的ICGXTemplate和IClientLocationService的注册信息,所以它退而求其次要求控制器提供无参构造函数来实例化,但你的项目明显用了构造函数注入,核心问题是补全依赖注册。
具体解决步骤
确认实现类存在
先检查项目里有没有实现ICGXTemplate和IClientLocationService的具体类,比如有没有CGXTemplate、ClientLocationService这类类,且它们正确实现了对应接口的所有方法。定位DI配置位置
老ASP.NET Web API(非Core)的DI配置通常在这些地方:App_Start/WebApiConfig.cs:如果用了Unity、Autofac等第三方容器,会在这里初始化容器并注册依赖Global.asax.cs的Application_Start方法:可能直接在这里配置容器
ASP.NET Core的话,配置在Startup.cs的ConfigureServices方法里,找类似services.AddScoped<IService, ServiceImpl>()的代码块。
注册新依赖
找到配置点后,把新增的接口和实现类注册进去:- 若用Unity容器:
container.RegisterType<ICGXTemplate, CGXTemplate>(); container.RegisterType<IClientLocationService, ClientLocationService>(); - 若用ASP.NET Core原生DI:
services.AddScoped<ICGXTemplate, CGXTemplate>(); services.AddScoped<IClientLocationService, ClientLocationService>();
(注:根据业务需求选择
AddScoped/AddTransient/AddSingleton,对应不同的依赖生命周期)- 若用Unity容器:
修复控制器代码
把构造函数里注释的参数和字段赋值打开,另外你代码里重复定义了IAppointmentTypeService字段(appointmentTypeService和apptTypeService),这大概率是笔误,建议清理冗余字段:public EstimatorController(IAppointmentTypeService appointmentTypeService, IClientCptCodeService cptCodeService, IStandAloneEstimatorService standAloneEstimator, IMedicareFeeImport medicareFeeService, IAPIRequestLogService requestLogService, ICGXTemplate cgxTemplateService, IClientLocationService locationService) { this.appointmentTypeService = appointmentTypeService; this.standAloneEstimator = standAloneEstimator; this.cptCodeService = cptCodeService; this.medicareFeeService = medicareFeeService; this.requestLogService = requestLogService; this.cgxTemplateService = cgxTemplateService; this.locationService = locationService; // 删除冗余的apptTypeService字段 }
临时应急方案(不推荐)
如果暂时找不到DI配置点,可以临时加一个无参构造函数,但这会跳过依赖注入,可能引发后续问题,仅用于测试:
public EstimatorController() { // 手动实例化依赖,比如: // cgxTemplateService = new CGXTemplate(); // locationService = new ClientLocationService(); }
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

