Home > other >  Application_Start event on ASP.NET Core 6.0
Application_Start event on ASP.NET Core 6.0

Time:10-12

How would I go about setting global variables in ASP.NET Core 6.0(razor pages)?

I have some information in the database, for example, ServiceName, ContactEmail and so on, and want to save it to my static class.

I don't want to access the database every time I need to display the information. In addition, there aren't Global.asax in ASP.NET Core .

In ASP.NET MVC 5 (based on .net framework), I could do it like

// global.asax
protected void Application_Start() {
  var context = new DefaultConnection();
  MyConfig.ServiceName = context.GlobalSettings.SingleOrDefault().ServiceName;
  // MyConfig is my static class
}

But I don't know where I should do it in ASP.NET Core project.
How can I do that? Please help me.

CodePudding user response:

I agree with @ProgrammingLlama here. Your best practice would be to create a singleton service that, on first use, will go to the database and fetch the static data, cache it, and then it will be used forever without ever going to the DB again. So basically a net result of lazy-loading.

However, if you want to force the fetching when the program is starting, I think you could create the singleton instance when you are configuring the DI services. The singleton's constructor would start the the data-fetching process and then you use the service as per normal.

If you tell me which option you prefer, I'll edit my answer to give you some sample code.

CodePudding user response:

This is sudo code

You can create a static class with static properties:

public static class MyConfig
{
    public static string Setting1 {set; get;}
    ...
}

then write a method to fetch data from your database and fill MyConfig and in the Program.cs file just call that method:

app.MapControllers();
app.Run();
CallYourMethodHere(); <-----

another is you can do this:

first create a static class:

public static class MyConfig
{
    private static Dictionary<string, string> MyConfigs {set; get;}
    
    private static Dictionary<string, string> GetConfigFromDatabase(bool forceToFill)
    {
        if(MyConfigs == null || MyConfigs.Any() == false || forceToFill == true)
        {
            //Fetch Data From Database and Fill MyConfig
        }
    }

    public static string GetConfig(string configName)
    {
        return GetConfigFromDatabase(false)[configName];
    }
}

In solution 2 you have to consider some thread-safe and race condition concepts.

  • Related