Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it appropriate to use Property Injection in a base class when a dependency is only required in the base class?

Example:

public abstract class BaseControler : Controller
{
    public IUnitOfWork UnitOfWork { get; set; }
}

public class HomeController : BaseControler
{
    readonly IUserRepository _userRepository;

    // :-)
    public HomeController(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }
}

We all know that we have to use Constructor Injection when the dependency is required. If it is an optional dependency we can use Property Injection instead.

But what should you do when only your base class requires the dependency?

When you would use Constructor Injection you would in my opinion pollute all derived classes.

public abstract class BaseControler : Controller
{
    readonly IUnitOfWork _unitOfWork;

    public BaseControler(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }
}

public class HomeController : BaseControler
{
    readonly IUserRepository _userRepository;

    // :-(
    public HomeController(IUserRepository userRepository, 
       IUnitOfWork unitOfWork) : base(unitOfWork)
    {
        _userRepository = userRepository;
    }
}

Is it approperiate to use Property Injection in a base class when a dependency is only required in the base class?

like image 926
Rookian Avatar asked May 04 '12 13:05

Rookian


1 Answers

You are not polluting the derived class. You are explicitly stating to the consumer that this class cannot function without this dependency.

If the base class requires this dependency in order to function properly, since the derived class derives from this base class, it implicitly requires this dependency as well. So the second example is the correct way. You shouldn't be using property injection for something that is a required dependency.

like image 80
Darin Dimitrov Avatar answered Sep 22 '22 12:09

Darin Dimitrov