Search code examples
c#singletonglobal-asax

How can I create a global object that is accessible in all the MVC & WEB API after it start and load information from file


I have a class that have a dictionaries that isbeing being load from local XML from App_Data. Where should I add that class to make it global and visible to all the controller in my application? I just one that the behave like a singleton. If a good option to add that in global.asax

Class example

  public class OptionsNames
        {
            private Dictionary<int, string> names;

            public OptionsNames()
            {

                names = new Dictionary<int, string>();

                names= LoadOptionsFromXML();

            }

            public string GetNameById(int id)
            {
                if (names.ContainsKey(id))
                     return names[id];

                return string.Empty;
            }
        }

Solution

  • It sounds like you just want a static object:

    public static class OptionsNames
    {
        private static Dictionary<int, string> names;
    
        static OptionsNames()
        {
            names = new Dictionary<int, string>();
            names = LoadOptionsFromXML();
        }
    
        public static string GetNameById(int id)
        {
            if (names.ContainsKey(id))
                 return names[id];
            return string.Empty;
        }
    
        // other class members
    }
    

    It doesn't really matter where the static class is located, it can be referenced from anywhere. Just make sure it's located in an intuitive location/namespace.

    Consuming code would simply invoke it directly without having to create an instance:

    var name = OptionsNames.GetNameById(someIdValue);