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

.NET中接口、基类与子类依赖注入服务注册问题

问题原因与解决方案

问题根源

你遇到的_authenticationService为null的问题,核心原因是**CompanyNoteService中重复定义了与父类NoteService同名的私有字段_authenticationService**:

  • 父类NoteService的_authenticationService已经通过构造函数注入了正确实例
  • 子类CompanyNoteService自己声明的同名字段没有被赋值(构造函数仅将参数传给父类),导致你在子类代码中访问的是这个未初始化的null字段

修复步骤

1. 移除子类中重复的字段声明

直接删除CompanyNoteService里的private readonly IAuthenticationService _authenticationService;,因为父类已经持有了该实例:

public class CompanyNoteService : NoteService {
    // 移除重复的字段声明
    public CompanyNoteService(IAuthenticationService authenticationService) : base(authenticationService) { }
    // 重写方法逻辑...
}

2. (可选)如果子类需要直接访问该字段,修改父类字段的访问修饰符

如果你的子类重写方法需要直接使用_authenticationService,将父类的字段从private改为protected,这样子类就能直接访问父类的实例:

public class NoteService : INoteService {
    // 修改为protected,允许子类访问
    protected readonly IAuthenticationService _authenticationService;

    public NoteService(IAuthenticationService authenticationService){
        _authenticationService = authenticationService;
    }
    // some code ...
}

3. 保持原服务注册代码不变

你的服务注册逻辑是正确的,无需修改:

services.AddScoped<IAuthenticationService, AuthenticationService>();
services.AddScoped<INoteService, CompanyNoteService>();

这样修改后,CompanyNoteService就能正确继承父类注入的IAuthenticationService实例,重写方法也能正常调用,控制器依赖注入的子类实例也能正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:48:06