Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put application startup logic in ASP.NET Core

I want to create a web service with ASP.NET Core 2.1 which checks on application startup if the connection to the database works and then prepares some data in the database.

The check runs in a loop till the connection was successful or the users presses Ctrl + C (IApplicationLifetime). It is important that no HTTP call is processed before the database was initialized. My question is: where to put this code?

I need a the dependency injection system to be fully initialized, so the earliest i can think of would be at the end of my Startup.Configure method, but the cancellation tokens on IApplicationLifetime do not seem to work there (properly because asp isn't fully started)

Is there a official place where can put this startup logic?

like image 549
Daniel Vetter Avatar asked Dec 23 '22 03:12

Daniel Vetter


1 Answers

You can build an extension method off of IWebHost which will allow you to run code before Startup.cs. Furthermore, you can use the ServiceScopeFactory to initialize any services you have (e.g. DbContext).

public static IWebHost CheckDatabase(this IWebHost webHost)
{
    var serviceScopeFactory = (IServiceScopeFactory)webHost.Services.GetService(typeof(IServiceScopeFactory));

    using (var scope = serviceScopeFactory.CreateScope())
    {
        var services = scope.ServiceProvider;
        var dbContext = services.GetRequiredService<YourDbContext>();

        while(true)
        {
            if(dbContext.Database.Exists())
            {
                break;
            }
        }
    }

    return webHost;
}

Then you can consume the method.

public static void Main(string[] args)
{
    BuildWebHost(args)
        .CheckDatabase()
        .Run();
}
like image 166
Travis Boatman Avatar answered Jan 06 '23 14:01

Travis Boatman