Dependency Injection is a horrible name (IMO)[1] for a rather straightforward concept. Here's an example:
- You have a method (or a class with methods) that does X (e.g. retrieve data from a 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 (i.e.
DbContext) from the method, and make it the caller's responsibility to provide this resource instead (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. 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).
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:
// Ignoring 'IDisposable' for simplicity
public class Repository
{
protected DbContext Context { get; }
public Repository(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 Repository(context);
// work
}