Dependency injection is a design pattern used to increase the maintainability and testability of applications by reducing the coupling between components.

In ASP.Net Core applications, DI is an essential part of the framework and is used to manage the lifetime and dependencies of services used throughout the application.

DI pattern lets you insert objects into your code at runtime.

DI loosens coupling and makes code more testable by eliminating the need to create or manage them.

 

DI works on this fundamental that instead of instantiating objects within a class, those objects are passed in as parameters to the class, like passing it to the constructor or the method instead.

This allows for greater flexibility in the way objects are created and managed, as well as easier testing of individual components.

 

 

DI in Asp.Net Core

ASP.Net Core provides a built in container that can be used to manage the dependencies of an application. 

The container is responsible for creating and managing instances of services which are registered with the container when the application starts.

 

 

Class without Using DI

  • we are instantiating the class inside the controller over here.
  • Drawback
    • Now later on, if the class name changes or we have to implement a different implementation of my service, then we have to change all the controllers or classes that uses this my service.

 

 

Class Using DI

This is what dependency injection does. We can easily inject the interface userService inside our application in the Program.cs file, and we also provide the implementation implementation detail of the interface of what we are trying to implement.

We can easily inject the service as a parameter to the controller or a parameter to the method, and then we can use this service throughout the application,

This is a good practice and it also satisfies the D in solid Principals

 

 

Add Connection String

 

 

Inject our services in program file

On the top over here we have the services that are injected inside the application before we actually build it.

We are injecting the dbcontext, which is of type application dbcontext inside the Program.cs file, which is the application itself, so that we can later on use the application Dbcontext to communicate the with the database from the controller or the repositories.

 


Related Question