_Dependency Injection_ is a horrible name <sup>_(IMO)_\[1\]</sup> for a rather straightforward concept. Here's an example:
1. You have a method (or class with methods) that does X *(e.g. retrieve data from a database)*
2. 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\*.
3. 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)
4. You are now doing dependency injection.
<br>
<sup>\[1\]</sup>: 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].
<br>
---
Edit: I figured some demo code would come handy for some, so here's one (in C#).
Without dependency injection:
<!-- language-all: lang-cs -->
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
}
[1]: https://en.wikipedia.org/wiki/DLL_injection
[2]: https://en.wikipedia.org/wiki/Dependency_Walker