asp-net-core-exception-handling icon indicating copy to clipboard operation
asp-net-core-exception-handling copied to clipboard

Retry and scoped services

Open YeskaNova opened this issue 5 years ago • 2 comments

Hi,

When you retry an inbound request, you reuse the same ServiceScope, I think that it's more natural and expected behavior to create a new Scope for each retry otherwise retries won't be independent to each other ( Imagine a DbContext as a ScopedService, we sure want to have a new DbContext ( Unit of Work ) for each retry ).

Yassine

YeskaNova avatar Dec 06 '19 14:12 YeskaNova

A workaround would be :

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseExceptionHandlingPolicies();
        app.Use(async (context,next)=> {
            try
            {
                await next();
            }
            catch
            {
                context.RequestServices = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope().ServiceProvider;
                throw;
            }
        });

It should be put somewhere like here.

The problem is that the Scope returned by CreateScope() is IDisposable and should be tracked somewhere to be Disposed when the request is finished. Do you have an idea how we can achieve this ?

YeskaNova avatar Dec 06 '19 14:12 YeskaNova

Hi,

Retry feature is obsolete, I would not recommend to retry entire request. Instead use retry in particular place where transient fault can occurs. For instance:

  • EF Core - https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
  • HttpClient - https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly
  • Generic use case - https://github.com/App-vNext/Polly

IharYakimush avatar Dec 07 '19 07:12 IharYakimush