Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core How to perform final actions on database when application is about to stop

I'm working on ASP.NET Core 3.1 application. I want to perform some final actions related to database while my application is about to stop. To do that I'm trying to call a function in my scoped service which is a additional layer between database and ASP.NET Core.

Startup.cs

public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime)
{
    lifetime.ApplicationStopping.Register(() =>
    {
        app.ApplicationServices.GetService<MyService>().SynchronizeChanges();
    });
}

But unfortunately i get Cannot resolve scoped service 'MyApplication.Services.MyService' from root provider error while I'm trying to do so.

like image 422
Nazar Antonyk Avatar asked Mar 07 '20 16:03

Nazar Antonyk


1 Answers

There is no scope when app is closing, so Asp.Net core is unable to create scoped service. Scope is created during http request only. If you do need to create scoped service without a scope, you can create scope manually:

public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime)
{
    lifetime.ApplicationStopping.Register(() =>
    {
        using (var scope = app.ApplicationServices.CreateScope())
        {
            scope.ServiceProvider
              .GetRequiredService<MyService>().SynchronizeChanges();
        }
    });
}

Also you can probably register your service as singleton or try to disable Asp.Net Core scopes validation (not recommended).

like image 90
ingvar Avatar answered Nov 19 '22 12:11

ingvar