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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With