'How to make a Dictionary accessible from all controllers in a .Net 5 API?

I have a Dictionary that will be populated with data from the database at startup, with a method that takes the key as a parameter, and returns the value. How to make the dictionary publicly accessible to all controllers? After searching, I learned that I would need to use Dependency Injection, but I'm failing at implementing it. Any resource that can get me on track is highly appreciated.



Solution 1:[1]

There are many ways to implement your question with/without DI. One of which is to write a static class that will be filled upon app startup.

No dependency injection:

  1. Declare a static class that contains your dictionary. By being static there would only be 1 instance on app start.
public static class StaticDictionary {
   public Dictionary<string,int> MyDictionary {get;set;}
}
  1. In your Startup.cs - Configure method, append your db context in the parameters.
public void Configure(..., YourDbContext dbContext)
  1. In the Configure method again, append your code that fills the dictionary.
public void Configure(..., YourDbContext dbContext){
   ...

   // no need to modify the code above this, just append the fill dictionary code
   foreach(var item in dbContext.TableName.ToList()){
      StaticDictionary.MyDictionary.Add(...);
   }
   
}
  1. In your controllers, you could access StaticDictionary without DI.
public IActionResult Index{
   var something = StaticDictionary.MyDictionary["Something"];

   return View();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jerdine Sabio