aspnetcore - How to Access Injection inside the "Configure" Method?

Viewed 75

In Asp.net core, inside the Startup class, I configured a class AccountService as an injection inside this method:

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddScoped(typeof(CharacterService));
}

I can successfully inject it on another class, but I want to also access CharacterService inside the Configure() method of Startup, because I want to call a method on the event of shut down of the server. Is it possible?

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime hostApplicationLifetime)
    {
        ...
        // var temp = app.ApplicationServices.GetService<CharacterService>();
        hostApplicationLifetime.ApplicationStopping.Register(() =>
        {
            //CharacterService.Instance.SaveMemoryInDatabase();
        });
    }

How can I access CharacterService inside the Configure method?

Thanks,

1 Answers

You can access service using app.ApplicationServices. In some cases you need to create a scope for services that are added scoped or transient. It often depends on where they were added. In case of the normal setup through ConfigureServices you need to create a scope. (Another place where services can be added is the host builder, which is often in the Program class.)

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddScoped<CharacterService>();
}

public void Configure(IApplicationBuilder app,
                      IWebHostEnvironment env,
                      IHostApplicationLifetime hostApplicationLifetime)
{
    using var scope = app.ApplicationServices.CreateScope();
    var characterService = scope.ServiceProvider.GetRequiredService<CharacterService>();

    hostApplicationLifetime.ApplicationStopping.Register(() =>
    {
        characterService.Instance.SaveMemoryInDatabase();
    });
}

CreateScope returns an IServiceScope which is disposable. All IDisposable services that are created for a scope, such as scoped and transient services, will be disposed when the IServiceScope is disposed.

Related