Have a look at Mark Seeman's blog or, even better, buy his book. It covers so much more than just DI. I appreciate you probably just want a simple sample to get going with. However, it's a subject that many who claim to understand don't and therefore worth learning well.
That said, here's a very simple example. The terminology, as I understand it, is
Inversion of Control and Dependency Injection. Inversion of Control refers to the fact that you give control of a class's dependencies to some other class, opposed to the class controlling the dependency itself, usually via the new
keyword. This control is exerted via Dependency Injection where a class is given, or injected, with its dependencies. This can be done via an IoC framework or in code (known as Pure DI). Injection can be performed in the class's constructor, via a property or as a method's parameter. Dependencies can be any type, they don't have to be abstract.
Here's a class that lists Tour de France winners who haven't doped:
class CleanRiders
{
List<Rider> GetCleanRiders()
{
var riderRepository = new MsSqlRiderRepository();
return riderRepository.GetRiders.Where(x => x.Doping == false);
}
}
This class is dependent on the MsSqlRiderRepository
. The class takes control of the creation of the instance. The problem is that this dependency is inflexible. It's hard to change it to a OracleRiderRepository
or a TestRiderRepository
.
IoC and DI solve this for us:
class CleanRiders
{
private IRiderRepository _repository;
public CleanRiders(IRiderRepository repository)
{
_repository = repository;
}
List<Rider> GetCleanRiders()
{
return _repository.GetRiders.Where(x => x.Doping == false);
}
}
Now the class is only depending on an Interface. Control of the dependency has been given up to the class's creator and must be injected via its constructor:
void Main()
{
var c = new CleanRiders(new MsSqlRepository());
var riders = c.GetRiders();
}
Arguably, a more flexible, testable and SOLID approach.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…