Monday, 5 October 2020

ASP.NET Core Dependency Injection

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

 public interface IHelloWorldService
 {
  string SaysHello();
 }
 
 public class HelloWorldServiceIHelloWorldService
 {
  public string SaysHello()
  { 
   return "Hello ";
  }
 }

Step 2: Add this service to Service container (service can either added by singleton, transient or scoped)

public void ConfigureServices(IServiceCollection services)
{
    ….
    …
    services.AddTransient<IHelloWorldServiceHelloWorldService>();
}

Step 3: Use this service as a dependency in the controller

public class HomeControllerController
{
    IHelloWorldService _helloWorldService;
    public HomeController(IHelloWorldService helloWorldService)
    {
    _helloWorldService = helloWorldService;
    }
}


Service lifetimes

Services can be registered with one of the following lifetimes:

  1. Transient
  2. Scoped
  3. 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.

services.AddSingleton<IHelloWorldServiceHelloWorldService>();


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.

services.AddTransient<IHelloWorldServiceHelloWorldService>();


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.

services.AddScoped<IHelloWorldServiceHelloWorldService>();


Reference: https://docs.microsoft.com

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives