Luis Naranjo
Luis Naranjo

Reputation: 669

How can I load a large dataset into memory on ASP.NET Core?

Context:

Question:

How can I load this data at initialization time, before HTTP requests start coming in? Do I do it in my controller's constructor? In my Startup.cs? I would appreciate some guidance here.

Thanks!

Upvotes: 0

Views: 1840

Answers (2)

Zen
Zen

Reputation: 631

I would do this in Configure method. Code should be something like this, then webapp will be available until data are pre-loaded.

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            //service should has been configured in ConfigureServices step
            //Create method to check if data loaded. If not then load them.
            serviceScope.ServiceProvider.GetService<ApplicationDbContext>().CheckDataLoaded();
        }
        //more steps here..

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039120

If you want to ensure that this data is loaded before calling any code in your controllers, then you could put it in the Startup class which is used for bootstrapping your application.

Upvotes: 1

Related Questions