ASP.NET Core | What problems does Dependency Injection solve?

Let's understand Dependency Injection with this C# example. A class can use a direct dependency instance as below.
Public class A {
MyDependency dep = new MyDependency();

public void Test(){
dep.SomeMethod();
}
}
But these direct dependencies can be problematic for the following reasons.
  • If you want to replace 'MyDependency' with a different implementation, then the class must be modified.
  • It's difficult to Unit Test.
  • If MyDependency class has dependencies, then it must be configured by class. If Multiple classes have dependency on 'MyDependency', the code becomes scattered.
DI framework solves these problems as below.
  • Use Interfaces or base class to abstract the dependency implementation.
  • Dependencies are registered in the Service Container provided by ASP.NET Core inside Startup class 'ConfigureServices' method.
  • Dependencies are injected using constructor injection and the instance is created by DI and destroyed when no longer needed.

Comments

Popular posts from this blog

ASP.NET Core | Change Token

ASP.NET Core | Open Web Interface for .NET (OWIN)

How will you improve performance of ASP.NET Core Application?