添加全局字典
本文关键字:字典 全局 添加 | 更新日期: 2023-09-27 18:35:09
我有一个 ASP.NET 的MVC应用程序。我需要一个在运行时在整个应用程序中可用的Dictionary<string, string>
。我的问题是,定义此Dictionary
的最佳位置/方法在哪里?我假设我需要在 Global.asax 文件中执行此操作。然而,我不确定。
创建一个实用程序类并使用 Lazy
来放置初始化,直到第一次命中:
public static class InfoHelper
{
private static Lazy<ConcurrentDictionary<string, string>> infoBuilder
= new Lazy<ConcurrentDictionary<string, string>>( () => SomeCreationMethod() );
public static ConcurrentDictionary<string, string> Info
{
get
{
return infoBuilder.Value;
}
}
或者,使用 HttpContext.Cache
:
public static class InfoHelper
{
public static ConcurrentDictionary<string, string> Info
{
get
{
ConcurrentDictionary<string, string> d
= HttpContext.Current.Cache["someId"] as ConcurrentDictionary<string, string>;
if (d == null)
{
d = HttpContext.Current.Cache["someId"] = SomeCreationMethod();
}
return d;
}
}
或者,从外部类设置此项时:
public static class InfoHelper
{
public static ConcurrentDictionary<string, string> Info
{
get
{
return HttpContext.Current.Cache["someId"] as ConcurrentDictionary<string, string>;
}
set
{
HttpContext.Current.Cache["someId"] = value;
}
}
然后从另一个类设置它:
InfoHelper.Info = ...;