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

Nazarion :

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.

ingvar :

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).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368638&siteId=1