c# class 继承自 base class ,带有依赖注入的构造函数

c# class inherits from base class with constructor with dependency injection

我有一个使用 Dependency Injection (Ninject) 的项目,其中我有以下 class:

public class SecurityService : BaseService
    {
        ISecurityRepository _securityRepo = null;

        public SecurityService(ISecurityRepository securityRepo)
        {
            _securityRepo = securityRepo;
        }
}

因为 BaseService 将在许多其他服务中被引用 classes 我想在那里添加一个方法,该方法也可以转到数据存储库并获取一些信息,所以我不必在其他服务中重复相同的代码 classes.

这是我要 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)'   

这个错误是有道理的,因为现在我有一个构造函数,我猜它正在期待一些东西。

Any clue how to fix this but that I can still have my dependency injection in BaseRepository class?

更新

我只是尝试删除构造函数并使用属性 [Inject] 但是在调试时我看到 _entityRepoNULL.

通过子 class 构造函数将 Repository 对象传递给基础 class:

public SecurityService(ISecurityRepository securityRepo) : base(IEntityRepository)
{
  //Initialize stuff for the child class
}

我可以让它工作:

我只是将私有 属性 转换为 public 然后 [Inject] 属性开始工作。

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

}

将依赖项添加到派生 class 的构造函数,并传递它。

public SecurityService(ISecurityRepository securityRepo, IEntityRepository entityRepo)
    : base(entityRepo) 
{
    _securityRepo = securityRepo;
}