How can we inject the service dependency into the controller?
There are three easy steps to add custom service as a dependency on the controller.
Step 1: Create the service
Step 2: Add this service to Service container (service can either added by singleton, transient or scoped)
Step 3: Use this service as a dependency in the controller
Service lifetimes
Services can be registered with one of the following lifetimes:
- Transient
- Scoped
- Singleton
Singleton
ASP.NET Core will create and share a single instance of the service through the application life. The service can be added as a singleton using AddSingleton method of IServiceCollection. ASP.NET Core creates service instance at the time of registration and subsequence request use this service instance. Here, we do not require to implement Singleton design pattern and single instance maintained by the ASP.NET Core itself.
Transient
Transient lifetime services are created each time they're requested from the service container. This lifetime works best for lightweight, stateless services. Register transient services with AddTransient.
In apps that process requests, transient services are disposed at the end of the request.
Scoped
Scoped lifetime services are created once per client request (connection). Register scoped services with AddScoped.
In apps that process requests, scoped services are disposed at the end of the request.
When using Entity Framework Core, the AddDbContext extension method registers DbContext types with a scoped lifetime by default.
Reference: https://docs.microsoft.com
0 comments:
Post a Comment