代码之家  ›  专栏  ›  技术社区  ›  VAAA

c#类通过依赖注入从具有构造函数的基类继承

  •  0
  • VAAA  · 技术社区  · 7 年前

    我有一个项目使用 Dependency Injection (Ninject)我有以下课程:

    public class SecurityService : BaseService
        {
            ISecurityRepository _securityRepo = null;
    
            public SecurityService(ISecurityRepository securityRepo)
            {
                _securityRepo = securityRepo;
            }
    }
    

    因为 BaseService

    这是我要的 BaseRepository :

    public partial class BaseService
        {
    
            IEntityRepository _entityRepo = null;
    
            public BaseService(IEntityRepository entityRepo)
            {
                _entityRepo = entityRepo;
            }
    
             public Settings AppSettings
            {
                get
                {
                    return _entityRepo.GetEntitySettings();
                }
            }
    }
    

    但是当我编译时,我得到以下错误:

    There is no argument given that corresponds to the required formal parameter 'entityRepo' of 'BaseService.BaseService(IEntityRepository)'   
    

    enter image description here

    有什么线索可以解决这个问题,但我仍然可以有我的依赖注入 上课?

    更新

    [Inject] 但当我看到 _entityRepo NULL .

    enter image description here

    3 回复  |  直到 7 年前
        1
  •  1
  •   John Wu    7 年前

    将依赖项添加到派生类的构造函数中,并将其传递。

    public SecurityService(ISecurityRepository securityRepo, IEntityRepository entityRepo)
        : base(entityRepo) 
    {
        _securityRepo = securityRepo;
    }
    
        2
  •  1
  •   Ryan Wilson    7 年前

    通过子类构造函数将存储库对象传递给基类:

    public SecurityService(ISecurityRepository securityRepo) : base(IEntityRepository)
    {
      //Initialize stuff for the child class
    }
    
        3
  •  1
  •   VAAA    7 年前

    我可以让它工作:

    [Inject] 属性开始工作。

    public partial class BaseService
        {
            [Inject]
            public IEntityRepository EntityRepo { get; set; }
    
    }