0

I have simple DbContext with interface which is registered as scoped service:

services.AddDbContext<ISomeDbContext, SomeDbContext>(cfg =>
{
    cfg.UseSqlServer(configuration.GetConnectionString("Default"), cfg =>
    {
        cfg.MigrationsAssembly(typeof(SomeDbContext).Assembly.FullName);
    });
});

Everything works fine, but up to a point. Some operations do not finish when I hold down F5 on the page, so I start spamming with refresh. Then I get an exception:

 An unhandled exception has occurred while executing the request.
      System.Threading.Tasks.TaskCanceledException: A task was canceled.

I can notice dozens of such exceptions, depending on how many times I refresh the page.

Operations finish when using DbContext as a transient (but it seems inefficient to me as I create a new instance on every request). However, a lot of exceptions are still thrown.

Besides, I can add that I only work on DbContext asynchronously (except for one Attach method call) and use the CancellationToken taken from HttpContext.RequestAborted everywhere.

Szyszka947
  • 473
  • 2
  • 5
  • 21
  • Actually Scoped service instantiated on each request. – Svyatoslav Danyliv Oct 23 '22 at 09:47
  • Yes I know, I meant that a new instance of Transient is created every time a service is requested (even inside the same HttpContext). – Szyszka947 Oct 23 '22 at 09:53
  • 1
    And what is the problem with this exception? You abort requests from client by holding F5, so server also aborts their execution to not waste resources. – Evk Oct 23 '22 at 11:54
  • The only problem here is that Transient updates the database and the correct data is returned to the user. When I use Scoped, the database also updates, but data isn't returned to the user. Then it causes further problems for my application. I would like the data not to be sent and the database not to update either. I don't know why this is happening, in `SaveChangesAsync` I also use `CancellationToken`. – Szyszka947 Oct 23 '22 at 14:06

0 Answers0