如何在MVC中使对象全局可访问

时间:2012-10-23 03:51:26

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

我为我的MVC应用程序创建了一个自定义缓存提供程序。我将使用此类将会话数据存储/检索到外部服务(如memcached或Redis)。

我想在应用程序启动时创建一次对象实例,以便我可以从任何控制器引用该对象,并且只需要对该实例进行一次“新建”。我在想我会在Global.asax Application_Start方法中实例化该类。但是,实例似乎无法在任何控制器中访问。

在MVC中实例化然后访问(全局)类的首选方法是什么?

以下是我的“简化”课程的副本:

 public class PersistentSession : IPersistentSession
    {
        // prepare Dependency Injection
        public ICache cacheProvider { get; set; }

        public bool SetSessionValue(string key, string value)
        {
            return cacheProvider.PutToCache(key, value);
        }

        public bool SetSessionValue(string key, string value, TimeSpan expirationTimeSpan)
        {
            return cacheProvider.PutToCache(key, value, expirationTimeSpan);
        }

        public string FetchSessionValue(string key)
        {
            return cacheProvider.FetchFromCache(key);
        }
    }

我想实例化它一次,以便我可以从应用程序的所有控制器访问它,如下所示:

 // setup PersistentSession object
 persistentSession = new PersistentSession();
 string memcachedAddress = WebConfigurationManager.AppSettings["MemcachedAddress"].ToString();
 string memcachedPort = WebConfigurationManager.AppSettings["MemcachedPort"].ToString();

 persistentSession.cacheProvider = new CacheProcessor.Memcached(memcachedAddress, memcachedPort);

MVC中的位置/如何实例化对象以从所有控制器获取全局访问权限?

1 个答案:

答案 0 :(得分:1)

我看不出问题!!

您所要做的就是将(static)关键字添加到PersistentSession类的方法定义中:

public class PersistentSession : IPersistentSession
{
    // prepare Dependency Injection
    public static ICache cacheProvider { get; set; }

    public static bool SetSessionValue(string key, string value)
    {
        return cacheProvider.PutToCache(key, value);
    }

    public static bool SetSessionValue(string key, string value, TimeSpan expirationTimeSpan)
    {
        return cacheProvider.PutToCache(key, value, expirationTimeSpan);
    }

    public static string FetchSessionValue(string key)
    {
        return cacheProvider.FetchFromCache(key);
    }
}

。并且您可以从任何地方使用以下代码访问它们:

PersistentSession.SetSessionValue (key , value);

您还可以添加静态构造函数以在访问任何成员之前初始化任何字段,并且在第一次访问静态类的成员之前调用构造函数,因此您可以确保在使用之前设置了类

public static PersistentSession ()
{
//Put your initializing code, for example:
cacheProvider = new CacheProvider();
}
相关问题