'Transient dependency injection with blazor server

Let's suppose a transient Service:

Startup.cs / ConfigureServices:

services.AddTransient<IMyService, MyService>();

Here is the content of the service:

interface IMyService
{
   public Task Traitement1();
   public Task Traitement2();
}

class MyService: IMyService
{
    MyDbContext _db;

    public MyService(MyDbContext db)
    {
       _db = db;
    }

    public async Task Traitement1()
    {
       var query = await _db.Table1.Where(...).SelectAsync(...);
       ...
       // Very long tasks, reading and writing database
       await _db.SaveChangesASync();
    }

    public async Task Traitement2()
    {
       var query = await _db.Table2.Where(...).SelectAsync(...);
       ...
       // Very long tasks, reading and writing database
       await _db.SaveChangesASync();
    }
}

I have a blazor page:

@inject IMyService service

I have 2 buttons: The first calls Traitement1 and the second calls Traitement2.

User can click on the first button and click on the second button without waiting the end of the first traitement.

I get an error message because 2 queries are running on the same dbcontext.

My question: How can i force framework to create 2 instances of MyService ?

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source