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

Dotnet Guru Archives