3

I have a web app (ASP .Net Core 1.1 MVC) which has some basic CRUD operations. The web app consumes a web API for all its operations.

The web app has some pages for editing, with basic textboxes and dropdown lists in them. Some of the dropdown lists contain static information - for example, there might be a lookup table with these values:

  1. Daily
  2. Weekly
  3. Monthly
  4. Yearly

The web API exposes an endpoint to retrieve these values. However, I obviously don't want to call this every time the user navigates to the Edit page. Since this is static data that will never change, I would like to read this lookup data from the API just once when the web app starts up. The thing is I'm not really sure where the best place to do this is. Should I put Main() in Program.cs, or in Startup() in Startup.cs? Or should it be done using DI (somehow... not sure how that would happen). is there some best practise for this scenario?

And then the next question is where should I store this data? Can I just create a static, global variable where I hold all lookup tables? This is data that applies to all users/sessions, so I thought a basic global key/value pair list would be fine? I can read this from my various controllers to populate the dropdown lists in the views?

Thanks... just wanna do this the right way. Any tips would be greatly appreciated.

RredCat
  • 5,259
  • 5
  • 60
  • 100
Fabricio Rodriguez
  • 3,769
  • 11
  • 48
  • 101

1 Answers1

9

You could save your data in singleton (application state data). You have to use Dependency Injection to make data available to all users:

  1. Define a service containing the data (for example, a class named MyAppData).

    public class MyAppData
    {
    // Declare properties/methods/etc.
    } 
    
  2. Add the service class to ConfigureServices (for example services.AddSingleton<MyAppData>();).

  3. Consume the data service class in each controller:

    public class MyController : Controller
    {
       public MyController(MyAppData myService)
       {
        // Do something with the service (read some data from it, 
        // store it in a private field/property, etc.)
       }
    } 
    

You could find more information in the article - Introduction to session and application state in ASP.NET Core (in the Application state data section)

Also, I recommend you to cache your data - Caching.

And finally, you could use localStorage on the frontend for persisting information that newer changes.

PS: You could use application state in a non-core website - https://stackoverflow.com/a/3733549/182344.

Glen Little
  • 6,951
  • 4
  • 46
  • 68
RredCat
  • 5,259
  • 5
  • 60
  • 100