Advertisement
Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Feb 10, 2023

Exploring Transient, Scoped, and Singleton using .NET and C#

Автор:
Abdelmajid BACO
Источник:
Просмотров:
1982

A Quick Guide to Transient, Scoped, and Singleton in C#.

In C#, the Transient, Scoped, and Singleton scopes are options for controlling the lifetime of objects which are created by dependency injection.

Transient

Transient objects are created each time they are requested. This means that if a Transient is injected into multiple consumers, each consumer will receive a separate instance of the object.

Scoped

Scoped objects are created once per request. This means that if a Scoped is injected into multiple consumers within the same request, they will all receive the same instance of this object. However, if the object is injected into multiple consumers in different requests, each request will receive its own instance of the object.

Singleton

Singleton objects are created the first time they are requested, and the same instance is used for all subsequent requests. This can be useful if you want to ensure that all consumers of a service are using the same instance of the object.

It is important to note that the Singleton should be used with caution. If for example the Singleton instance is modified simultaneously by multiple consumers. This can cause concurrency issues.

Code Example

Here is an example of using the scopes in a .NET project. This example shows how to register a service with .NET dependency injection system, and how to inject and use the service in a consumer class.

First, let’s define the service interface and its implementation:

public interface IMyService
{
    void DoWork();
}

public class MyService : IMyService
{
    public void DoWork()
    {
        Console.WriteLine("Doing work in MyService");
    }
}

Next, we can inject and use the IMyService service in a consumer class:

public class Consumer
{
    private readonly IMyService _myService;

    public Consumer(IMyService myService)
    {
        _myService = myService;
    }

    public void DoWork()
    {
        _myService.DoWork();
    }
}

Use Transient

We can register the Transient service in the ConfigureServices method of the Startup class:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyService, MyService>();
}

In this example, each time the Consumer class is created or the DoWork method is called, a new instance of the MyService class will be created and injected into the Consumer class.

Use Scoped

We can register the Scoped service in the ConfigureServices method of the Startup class:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IMyService, MyService>();
}

In this example, the MyService class will be created the first time it is requested within a given request, and the same instance will be used for all subsequent requests for the MyService class within the same request. If the Consumer class or the DoWork method is called in a different request, a new instance of the MyService class will be created and injected.

Use Singleton

We can register the Singleton scope service in the ConfigureServices method of the Startup class:

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IMyService, MyService>();
}

In this example, the MyService class will be created the first time it is requested, and the same instance will be used for all subsequent requests for the MyService class.

Conclution

In general, it’s best to use the Transient scope whenever possible, and to use the Scoped or Singleton scopes only when necessary to maintain state or ensure that all consumers are using the same instance of a service.

Похожее
Feb 20
Author: Olorundara Komolafe
Scheduling one or more background tasks is almost inevitable when building robust, self-sustaining APIs with .NET. A few packages have been around for years, such as Hangfire and Quartz.NET.ASP.NET Core allows background tasks to be implemented as hosted services. However,...
May 13, 2023
Author: Juan Alberto España Garcia
Introduction to Async and Await in C#Asynchronous programming has come a long way in C#. Prior to the introduction of async and await, developers had to rely on callbacks, events and other techniques like the BeginXXX/EndXXX pattern or BackgroundWorker.These methods...
29 июля 2019 г.
От переводчика: некоторые скорее всего уже читали этот титанический труд от Мартина Фаулера и его коллеги Джеймса Льюиса, но я все же решил сделать перевод этой статьи. Тренд микросервисов набирает обороты в мире enterprise разработки, и эта статья является ценнейшим...
May 8, 2023
Author: Waqas Ahmed
Dapper is a lightweight ORM (Object-Relational Mapping) framework for .NET Core and is commonly used to query databases in .NET Core applications. Here are some of the advanced features of Dapper in .NET Core: Multi-Mapping: Dapper allows...
Написать сообщение
Почта
Имя
*Сообщение


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban