VAAA
VAAA

Reputation: 15049

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)'   

enter image description here

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.

enter image description here

Upvotes: 1

Views: 2555

Answers (3)

John Wu
John Wu

Reputation: 52280

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

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

Upvotes: 2

VAAA
VAAA

Reputation: 15049

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; }

}

Upvotes: 2

Ryan Wilson
Ryan Wilson

Reputation: 10800

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
}

Upvotes: 1

Related Questions