One-time code execution when starting a WebAPI application

Viewed 38

A task:

When starting the application, you need to check if there is a default user in the database, if not, then create a user.

How to make and where to write such a check so that it is executed only once at the start of the application?

It is necessary to be able to work with scoped services.

I thought about IHostedService service, but it is a singleton.

One option is to write the code in a Program.cs

var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<WeatherDbContext>();
    // do something
}

But if there is a lot of code, then posting it here is not correct.

How to move the code to some class, and then only its call remains?

1 Answers

https://jasonwatmore.com/post/2019/12/27/aspnet-core-automatic-ef-core-migrations-to-sql-database-on-startup#:~:text=Use%20the%20EF%20Core%20DB,database%20by%20calling%20the%20Database.

Register the EF Core DB Context as an ASP.NET Core Service The Entity Framework Core DB Context is registered as a service with the ASP.NET Core Dependency Injection (DI) system from the ConfigureServices() method of the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataContext>(x => x.UseSqlite("Data Source=LocalDatabase.db"));

    ...
}

Use the EF Core DB Context Service to automatically migrate database changes An instance of the EF Core DB Context service is injected as a parameter into the Configure() method of the Startup.cs file, the DB Context instance is then used to apply any pending migrations to the database by calling the Database.Migrate() method.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
{
    // migrate any database changes on startup (includes initial db creation)
    dataContext.Database.Migrate();

    ...
}
Related