添加全局字典

时间:2014-12-22 15:02:53

标签: c# asp.net .net asp.net-mvc

我有一个ASP.NET MVC应用程序。我需要一个在运行时在整个应用程序中可用的Dictionary<string, string>。我的问题是,定义此Dictionary的最佳位置/方式在哪里?我假设我需要在Global.asax文件中执行此操作。但是,我不确定。

1 个答案:

答案 0 :(得分:1)

创建一个实用程序类并使用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 = ...;