Reputation: 21975
I'd like to instantiate a class when I start the application and then use that object in every class (custom ValidationAttribute
s, controllers, etc).
Where should I instantiate that class to have access to it everywhere?
I'm using ASP.NET MVC with C#.
Upvotes: 2
Views: 3890
Reputation: 17784
Besides the choices already given, you can use dependency injector to control the management and lifetime of expensive objects. Castle Windsor, Ninject and StructureMap play well with asp.net mvc.
Upvotes: 4
Reputation: 6878
It sounds like you are wanting to create a Singleton class. This article has many examples of how to achieve this, and their caveats. From the article, this is probably the simplest way to create a singleton:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Anywhere in your code you need to access your class, you would write Singleton.Instance.MyMethod()
(following the above example), much like you access string.IsNullOrEmpty()
. Aside of the boiler plate code included above, you can code your properties and methods as you would any other class.
Upvotes: 2
Reputation: 150108
I place such object instances in the HttpRuntime Cache.
public static MyCacheHelper
{
public static MyType GetMyInstance
{
get
{
if (HttpRuntime.Cache[MY_CACHE_KEY] == null)
{
HttpRuntime.Cache[MY_CACHE_KEY] = new MyType();
}
return (MyType)HttpRuntime.Cache[MY_CACHE_KEY];
}
}
}
Upvotes: 3
Reputation: 28064
You could make it a static property of the MvcApplication class (global.asax), and instantiate it in Application_Start.
Upvotes: 3