.NET

Dependency Injection Scopes


ASP.NET Core DI is a service that is very useful in controlling the dependencies of objects in our application. DI is the design pattern that is being implemented to maximize the decoupling of software systems. Unlike most of the designs that produce dependencies (Objects or services) within the class, these are provided by another object outside the class, often through the class constructor.

 In .NET Core, services can be registered with different lifetimes or scopes:

 

Transient

A new instance takes its place every time a service has been called for.

It is used to serve lightweight and stateless services.

services.AddTransient<IMyService, MyService>();  

Scoped

A single instance is created at a time which is per request (for example per HTTP request in a web application).

Why: it is used if you need a service that has to remember state throughout the lifecycle of a request. services.AddScoped<IMyService, MyService>();

 

Singleton

The instance is instantiated and used in the application from its initiation till its termination.

Use when the resource is a large heavy item that must be used by a number of people such as the log files or configuration files. services.AddSingleton<IMyService, MyService>(); 

Example

Demonstration of how different scopes work when injecting a service in a controller.

using Microsoft.AspNetCore.Mvc;using System;public interface IMyService{ string GetMessage();}public class MyService : IMyService{ private readonly string _instanceId; public MyService() { _instanceId = Guid.NewGuid().ToString(); } public string GetMessage() => $"Instance ID: {_instanceId}";}[ApiController][Route("api/test")]public class TestController : ControllerBase{ private readonly IMyService _service1; private readonly IMyService _service2; public TestController(IMyService service1, IMyService service2) { _service1 = service1; _service2 = service2; } [HttpGet] public ActionResult Get() { var message1 = _service1.GetMessage(); var message2 = _service2.GetMessage(); return Ok(new { Message1 = message1, Message2 = message2 }); }}

 

Output : 

In Transient Case

Two different instances (service1 and service2) are created even within the same request.

{ "Message1": "Instance ID: 02915337-838c-4377-827a-7dfc5d2f5561", "Message2": "Instance ID: 2c29baec-feec-49ae-b163-c07e0a907a8e"}

In Scoped and Singleton Case

  • Scoped: The same instance (service1 and service2) is reused within the same request.
  • Singleton: Same instance throughout the application. { "Message1": "Instance ID: 2c29baec-feec-49ae-b163-c07e0a907a8e", "Message2": "Instance ID: 2c29baec-feec-49ae-b163-c07e0a907a8e" }

 Ready to transform your business with our technology solutions?Contact Us today to Leverage Our .Net Expertise.

0

.Net

Related Center Of Excellence