Home > Net >  .NET Core 6.0 Custom Boostrap Service
.NET Core 6.0 Custom Boostrap Service

Time:03-08

I am new to .net core 6.0. I wish to understand if we can initialize a custom data cache implementation at the start of the application.

I tried Middleware but, this executes on every request (can use but not ideal). I tried Hosted services, but could not find much help.

Any help is highly appreciated.

CodePudding user response:

You can retrieve a service and run your bootstraping logic before the application is started in your Program.cs, similarly to this:

var builder = WebApplication.CreateBuilder(args);

// register services...

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var bootstrapperService = scope.ServiceProvider.GetRequiredService<BootstrapperService>();
    bootstrapperService.Bootstrap();
}

app.MapGet("/", () => "Hello World!");

app.Run();

Note that creating a scope is only necessary if your BootstrapperService is scoped.

  • Related