Dependency Injection (DI), which allows you to inject objects into a class, rather than relying on the class to create the object itself.
When a component creates a private instance of another class, it internalizes the initialization logic within the component. This initialization logic is rarely reusable outside of the creating component, and therefore must be duplicated for any other class that requires an instance of the created class.
1. FactoryThe use of a factory class is one common way to implement DI
1. It is not reusable across other applications.
2. Frequently all of the available creation options are hardcoded into the factory implementation, making the factory itself non-extensible.
3. Also, most of the time the class calling the factories' creation methods must know which subclass of the factory to create.
4. All dependencies for an object that is created using a factory are known to the factory at compile time. At run time there is no way to insert or alter the manner in which objects are created, or which dependencies are populated.
5. Since factories are custom to each individual implementation, there can be a significant level of cross-cutting infrastructure that is held captive inside a particular factory.
6. Factories rely on well-defined interfaces to achieve polymorphism. In order for a factory implementation to be able to dynamically create different concrete subclass instances, there must be a common base class or shared interface implemented by all classes that the factory will create. Interfaces decouple the construction of the object from the specific implementation of the interface. The dilemma that arises now is how you can accomplish this decoupling without being forced to create an interface for everything.
2. ContainersDI containers provide generic factory classes that instantiate instances of classes. These instances are then configured by the container, allowing construction logic to be reused on a broader level.
They provide
1. Not only factories for creating objects.
2. Also, dependency resolution.
For more details, please refer to MSDN article.
MSDN article