Issues without Depencency Injection:
- Suppose a controller has to instantiate a class which is a service and the controller has to do it in multiple functions, now, if the service name changes then we will have to rename that service in all those places it has been used in the controller, this is an example of tight coupling.
- Dependecy injection solves it
Dependency Injection is a software design pattern, it helps us to develop loosely-coupled code that is easy to maintain.
- With dependency injection, we can reduce the hard-coded dependencies among the classes by injecting those depenedencies at the runtime instead of design time technically.
- Comes built-in with .NET Core
- .NET Core injects objects of dependency classes through constructor or method by using built-in IoC(Inversion of Control) container
- In ASP.NET Core, both framework services and application services can be injected into classes, rather than being tighlty coupled
- Dependency Injection is an integral part of ASP.NET Core
- Dependency Injection is a form of IoC (Inversion of Control)
- Dependency Injection is the fifth principle of S.O.L.I.D.
- i.e. A class should depend on abstractions and not upon the implementations
- A class should concentrate on fulfilling its responsibility and not on creating objects that it requires to fullfil those responsibilities and that is where dependecy injection comes into picture, it provides the class with required objects
- ASP.NET Core has built-in oC Container
- The built-in container is represented by IServiceProvider implementation that supports constructor injection by default
- The Types or Classes that are managed by IoC container are called Services
- There are two types of services in ASP.NET Core
- Framework Services : Part of ASP.NET Core
- e.g. IApplicationBuilder, IWebHostEnvironment, ILogger<T> etc.
- Application Services : Programmer writes, custom services
- Let's take an example of Constructor Dependecy Injection
- We register the Services in IoC container
- services.AddTransient<IInterface, ImplementationOfInterface>();
- Only after that we can use the injected serrvices in constructors
- Interfaces play a very important role as the controller is only aware of the Interface and not the implemetation
- It is advantageous in term of testing the code too
Example of DI setup:
- In the following snippet of code, the 5th line is registering MyDependency class in the IoC (Inversion of Control) container.
- And this is how you inject it in the controller:
internal class Student
{
private readonly IMyDependency _myDependency;
public void Student(IMyDependency myDependency)
{
_myDependency = myDependency;
}
}
Read more about Dependency Injection here
Read more about Service lifetimes here
Comments
Post a Comment