简体   繁体   中英

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

I have a project using Dependency Injection (Ninject) where I have the following class:

public class SecurityService : BaseService
    {
        ISecurityRepository _securityRepo = null;

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

Because BaseService is going to be referenced in many other service classes I wanted to add there a method that also go to Data Repository and get some information so I don't have to repeat the same code along the other service classes.

Here is what I have for BaseRepository :

public partial class BaseService
    {

        IEntityRepository _entityRepo = null;

        public BaseService(IEntityRepository entityRepo)
        {
            _entityRepo = entityRepo;
        }

         public Settings AppSettings
        {
            get
            {
                return _entityRepo.GetEntitySettings();
            }
        }
}

But when I compile I get the following error:

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

在此处输入图片说明

And the error make sense because now I have a constructor that I guess is expecting something.

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

UPDATE

I just tried to remove the constructor and use the attribute [Inject] but when debugging I see that _entityRepo is NULL .

在此处输入图片说明

Pass the Repository object to the base class via the child class constructor:

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

Add the dependency to the constructor for the derived class, and pass it along.

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

I could make it work:

I just convert the private property to be public and then [Inject] attribute started to work.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM