I have created a custom caching provider for my MVC application. I will use this class to store/retrieve session data to an outside service (like memcached or Redis).
I would like to create the object instance once at application start so that I can reference the object from any controller, and only have to ‘new up’ the instance once. I was thinking that I would instantiate the class in the Global.asax Application_Start method. However, the instance does not seem to be accessible in any of the controllers.
What is the preferred way to instantiate and then access a (global) class in MVC?
Here is a copy of my ‘simplified’ class:
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);
}
}
I want to instantiate it one time so that I can access it from all controllers application wide, something like this:
// 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);
Where/How in MVC should the object be instantiated to get global access from all controllers?
I can’t see the problem !!
all you have to do is to add (static) keyword to the definition of the methods of PersistentSession class:
. and you can access them using the following code from anywhere :
you can also add a static constructor to initialize any fields before accessing any member, and the constructor is called before a member of static class is accessed for the first time, so you can be sure that your class is set before being used.