Fabricio Rodriguez
Fabricio Rodriguez

Reputation: 4239

I need to execute an async method at startup in an ASP .Net Core 3.1 Web API

I have an ASP .Net Core 3.1 Web API. When the API starts, I would like it to read a couple of lookup tables from a database and store them somewhere. These tables contain data that rarely ever changes (titles, countries, languages, etc.) It's data that maybe changes once every few years. So, I would like them to be read and stored upon startup to increase performance, instead of reading the database every time I need this data.

What I did is to create a service that reads all of these lookup tables. Then, in the services' constructor, I call a method in the service which does the actual reading from the database. I then registered this service as a Singleton in Startup.ConfigureServices().

The problem is that the method that does the reading of the database tables is async, and the constructor cannot be async (as far as I understand).

Currently, it's working - the method is called in the service's constructor, which then returns immediately, while the reading of the database tables happens in a separate process. The actual reading only takes like a second or two anyway. However, I don't like this. Another code could run which requires access to this lookup data, but the data might not be ready yet. Ideally, I would like the reading of these lookup tables to complete before any other code is executed. Also, I get a green wiggly line in VS with a warning about this :)

So I'm not sure how to fix it. Is there a best practice for executing code at startup in a .Net Core API?

Upvotes: 2

Views: 3331

Answers (1)

puko
puko

Reputation: 2970

You can do it in the main method. Since C# 7.1 can application entry point return Task.

Take a look at this example. He runs his migrations in the main method (but he mentions that it's a bit messy, so you can use another approach described in the article). I think you can load your data in the same way.

https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-part-2/

Upvotes: 2

Related Questions