Home > Software engineering >  How to create a global variable in ASP.NET Core Web API application?
How to create a global variable in ASP.NET Core Web API application?

Time:02-21

How can I create a global variable in an ASP.NET Core Web API application? In ASP.NET MVC, I could do it like:

Application["<variableName>"] = <value>

I tried the same in my web API application, but was unable to find an equivalent for this. I saw some solutions which suggested me to store the data appsettings.json, but since the data I want to store in the global variable is not static, I cannot use that setup. I need to set different data during runtime. How can I do that? Please help me.

CodePudding user response:

somewhere in project

public static class Config{
       public static Dictionary<string,string> Application = new Dictionary<string,string>();
}

elsewhere

Config.Application["froop"] = "noodle";

of course you will have to deal with race conditions, etc

CodePudding user response:

We could use Singleton_pattern , creating an Application static object in .net core.

we can also try to use Depend Injection, register a singleton object as below in your code.

Writing a property ConcurrentDictionary in ApplicationInstance class.

public class ApplicationInstance {

    public ConcurrentDictionary<string,object> Application { get; } = new ConcurrentDictionary<string, object>();
}

public void ConfigureServices(IServiceCollection services){
    services.AddSingleton<ApplicationInstance>();
}

Then we might use this object

public class HomeController : ControllerBase
{
    private readonly ApplicationInstance _application;

    public HomeController(ApplicationInstance application)
    {
        this._application = application;
    }
    
    //use _application["test"] instance in your code
}

I would use ConcurrentDictionary to help us avoid racing-condition which will be happened on multiple-thread accessing the same object concurrently.

  • Related