How to implement public dictionary?

winanjaya 146 Reputation points
2022-11-18T05:23:55.11+00:00

How to implement a public dictionary in ASP MVC NET 6 like:

Dictionary<string, string> My_dict1 = new Dictionary<string, string>();

that can be maintained (add/edit/delete) dictionary items from all classes?

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-11-18T07:01:01.87+00:00

    Hi @winanjaya ,

    How to implement public dictionary?

    You can use the following methods:

    1. Use a Static class:
      public static class GlobalData  
      {  
          public static Dictionary<string, string> Application { get; set; } = new Dictionary<string, string>();   
      }  
      
      Then, in the controller, use the following code to get or set the value:
          GlobalData.Application.Add("Name", "Tom");  
          var name = GlobalData.Application["Name"];  
      
    2. Use Asp.net core Singleton pattern Create a class:
      public class ApplicationInstance  
      {   
          public Dictionary<string, object> Application { get; } = new Dictionary<string, object>();  
      }  
      
      Register the class using AddSingleton in the program.cs file:
      builder.Services.AddSingleton<ApplicationInstance>();  
      
      Then, refer the following code to use it:
      public class AccountController : Controller  
      {  
          private readonly ApplicationInstance _app;  
          public AccountController(ApplicationInstance application)  
          {  
              _app = application;  
          }  
          public IActionResult Index()  
          {  
              var name = GlobalData.Application["Name"];  
      
              var name2 = _app.Application["Name"];  
              return View();  
          }  
      }  
      
      The output as below:

    261768-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.