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.
- 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
Post a Comment