Dependency Injection is a horrible name (IMO) 1 for a rather straightforward concept. Here's an example:
- You have a method (or class with methods) that does X (e.g. retrieve data from database)
- As part of doing X, said method creates and manages an internal resource (e.g. a
DbContext
). This internal resource is what's called a dependency
- You remove the creating and managing of the resource (ie
DbContext
) from the method and make it the caller's responsibility to provide this resource (as a method parameter or upon instantiation of the class)
- You are now doing dependency injection.
\[1\]: I come from a lower-level background and it took me months to sit down and learn dependency injection because the name implies it'd be something much more complicated, like *[DLL Injection][1]*. The fact that Visual Studio (and we developers in general) refers to the .NET libraries (DLLs, or _assemblies_) that a project depends upon as _dependencies_ does not help at all. There is even such a thing as the [Dependency Walker (depends.exe)][2].
[Edit] I figured some demo code would come handy for some, so here's one (in C#).
Without dependency injection:
public class Repository : IDisposable
{
protected DbContext Context { get; }
public Repository()
{
Context = new DbContext("name=MyEntities");
}
public void Dispose()
{
Context.Dispose();
}
}
Your consumer would then do something like:
using ( var repository = new Repository() )
{
// work
}
The same class implemented with the dependency injection pattern would be like this:
public class RepositoryWithDI
{
protected DbContext Context { get; }
public RepositoryWithDI(DbContext context)
{
Context = context;
}
}
It's now the caller's responsability to instantiate a DbContext
and pass (errm, inject) it to your class:
using ( var context = new DbContext("name=MyEntities") )
{
var repository = new RepositoryWithDI(context);
// work
}