Dependency Injection

  • Is a software design pattern that implements inversion of control for resolving dependencies.
  • Is a style of object configuration in which object’s fields and collaborators are set by an external entity.   In other words objects are configured by an external entity.
  • Using DI objects are given their dependencies at run time rather than compile time.
  • It helps us to create loosely coupled classes.
  • When two classes are tightly coupled, they are linked with a binary association. You might have two classes Class1 and Class2 that are joined together as an aggregation.
public class Class1
{
    public Class2 Class2 { get; set; }
}
 
public class Class2
{
}

Three types of DI

Constructor Injection
  • The dependencies are provided through a class constructor.
Setter Injection
  • The client exposes a setter method that the injector uses to inject the dependency.
Interface Injection
  •  The dependency provides an injector method that will inject the dependency into any client passed to it.
  • Clients must implement an interface that exposes a setter method that accepts the dependency