In object-oriented programming (OOP) software design, dependency injection (DI) is the process of supplying a resource that a given piece of code requires. The required resource, which is often a component of the application itself, is called a dependency.
One way of structuring the code is to map the location of each required resource. Another way is to use dependency injections and have an external piece of code assume the responsibility of locating the resources. Typically, the external piece of code is implemented by using a framework, such as Spring for Java applications.
Another benefit of dependency injection is that injected resources can be customized through XML files which are outside the source code. This allows changes to be applied without having to recompile the entire codebase.
However, dependency injection can sometimes make troubleshooting difficult, as a great deal of code is pushed into an unknown location that creates resources and distributes them as needed across the application. Debugging code when all of the objects that are misbehaving are buried in a complicated third-party framework can be very frustrating and time-consuming.
There is more than one way to implement dependency injection. The most common way is using constructor injection, which requires that all software dependencies be provided when an object is first created. However, constructor injection makes the assumption that the entire system is using the pattern, which means the entire system must be refactored at the same time. This is difficult, risky and time-consuming.
While there is some confusion and debate as to the relationship between inversion of control and dependency injection, the latter is generally considered one specific style of the former. According to Martin Fowler, chief scientist at ThoughtWorks, the confusion arises due to the rise of IoC containers. "The name is somewhat confusing (and ironic) since IoC containers are generally regarded as a competitor to Enterprise JavaBeans (EJB), yet EJB uses inversion of control just as much (if not more)," according to Fowler.
There are three main styles of dependency injection, according to Fowler: Constructor Injection (also known as Type 3), Setter Injection (also known as Type 2), and Interface Injection (also known as Type 1).
I also suggest you register this as factory function in your container to not have the code you posted in your consumer code - that would not be dependency injection but rather the anti pattern of service locator because you gained nothing but traded constructor calls with resolve calls. 2b1af7f3a8