Hi @winanjaya ,
How to implement public dictionary?
You can use the following methods:
- Use a Static class:
Then, in the controller, use the following code to get or set the value:public static class GlobalData { public static Dictionary<string, string> Application { get; set; } = new Dictionary<string, string>(); }
GlobalData.Application.Add("Name", "Tom"); var name = GlobalData.Application["Name"];
- Use Asp.net core Singleton pattern Create a class:
Register the class using AddSingleton in the program.cs file:public class ApplicationInstance { public Dictionary<string, object> Application { get; } = new Dictionary<string, object>(); }
Then, refer the following code to use it:builder.Services.AddSingleton<ApplicationInstance>();
The output as below: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(); } }
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