Home > Software engineering >  How to delare global variables and access them in .net 6 webapi controllers?
How to delare global variables and access them in .net 6 webapi controllers?

Time:02-25

I'm using VS2022 to create a webapi(.net6) project and trying to declaare somme gloabal variables which will be used among webapi controllers. What I did this way: Project structure

Declared static variable of type Dictionary at the top level folder of the project:

namespace CenterWebApiHub
{
    public static class ParkCenterConfigs
    {
        public static ConcurrentDictionary<string, string> MapToConnections = new 
            ConcurrentDictionary<string, string>();
     }
}

How to access this static Dictionary from Webapi controllers? Please help

CodePudding user response:

If it is supposed to be read-only, like settings, you should look into dependency injection. The documentation can be found here.

If you want to write to this variable, you need another concept. There is no guarantee that this variable will not be wiped when your application pool recycles and it's is not scalable at all. If you ever have to load balance your application, a variable in memory of one server won't cut it.

You did not say what you need it for, but a global variable in memory is the worst way to handle it. Maybe you should start by looking for concepts of the thing you want to do. I'm sure others have handled it before, look how they did it and why.

  • Related