c# – Dependency Injection in Controller Base

Question:

Well I'm learning to work with dependency injection now and I would like to apply it in my project. But I came across the following difficulty, I have a base controller where it is inherited by three other base controllers that perform the overload and so I can perform all the necessary functions on my system. But when trying to apply dependency injection the child classes ask me to pass the constructor object, so I would like to know how to deal with this.

I'm using unity to inject dependencies.

Below is the code of the parent controller:

public class BaseController : ApiController
{
    public string[] includes = null;

    private readonly IFiltroServico servico;
    public BaseController(IFiltroServico _servico)
    {
        servico = _servico;
    }
}

Contoller daughter, here the error is generated because it is necessary to pass the IFiltroService due to the constructor of the parent class:

public abstract class BaseController<R> : BaseController
        where R : class
    {
 //services da controller;
    }

I want to know how best to do this and how to pass the constructor from here .

Answer:

When you inherit a class that has a constructor with parameters, it is necessary to pass this to its base , that is, you need to pass the IFiltroServico in the base

public abstract class BaseController<R> : BaseController
        where R : class
{
    public BaseController(IFiltroServico servico)
        :base(servico)
    {

    }
}

obs: the underscore before the variable name is a convention to indicate that the variables are private, in which case it "should" be in the private property, since the IFiltroServico passed as a parameter in the constructor is only in that scope.

EDIT

Here's an example I usually use when I use the Repository pattern

public abstract class CrudRepository<TEntity, TKey> : ICrudRepository<TEntity, TKey>
    where TEntity : class
{
    protected DbContext _context;
    public CrudRepository(DbContext context)
    {
        _context = context;
    }

    //Codigo aqui
} 

public class UsuarioRepository : CrudRepository<Usuario, int>
{
    public UsuarioRepository(DbContext context) : base(context)
     { }       
}
Scroll to Top