Blake Rivell
Blake Rivell

Reputation: 13875

Using inheritance and dependency injection at the same time

Here is how my application makes a call to the database: Web App -> Business Layer -> Data Layer

Everything is using dependency injection.

For example:

In the controller in my Web app I make a call like this:

await _manager.GetCustomers();

Which goes into my Business Layer:

public class CustomerManager : ICustomerManager
{
    private ICustomerRepo _repository;
    public CustomerManager(ICustomerRepo repository)
    {
        _repository = repository;
    }

    public Task<IList<Customer>> GetCustomers(string name = null)
    {
        return _repository.GetCustomers(name);
    }
}

Which goes into my Data Layer:

public class CustomerRepo : BaseRepo, ICustomerRepo
{
    public CustomerRepo(IConfigurationRoot configRoot) 
    : base(configRoot)
    {
    }

    public Customer Find(int id)
    {
        using (var connection = GetOpenConnection())
        {
            ...
        }
    }
}

The trick here is that CustomerRepo inherits from BaseRepo to be able to use the GetOpenConnection() function. But at the same time BaseRepo needs an IConfigurationRoot injected into it from the web application. How can I do both?

public class BaseRepo
{
    private readonly IConfigurationRoot config;

    public BaseRepo(IConfigurationRoot config)
    {
        this.config = config;
    }

    public SqlConnection GetOpenConnection(bool mars = false)
    {
        string cs = config.GetSection("Data:DefaultConnection:ConnectionString").ToString();
        ...
    }
}

Upvotes: 2

Views: 669

Answers (1)

Ryan M
Ryan M

Reputation: 2112

How would you instantiate (or even compile) a CustomerRepo at all, regardless of dependency injection? You need an IConfigurationRoot parameter to pass through to the base constructor. Like:

public CustomerRepo(IConfigurationRoot configRoot) 
    : base(configRoot)
{
}

See https://msdn.microsoft.com/en-us/library/hfw7t1ce.aspx for info on the base keyword.

Upvotes: 4

Related Questions