nerdperson
nerdperson

Reputation: 297

C# .NET Singleton life of app pool

I want to create a singleton that remains alive for the life of the app pool using HttpContent.Current.Cache.

Where would I create the class and how should it be implemented? I understand how to implement a singleton but am not too familiar with threading and httpcontent.current.cache.

Thanks!

Upvotes: 2

Views: 2042

Answers (3)

Xaqron
Xaqron

Reputation: 30857

It doesn't matter where to put the singleton code.

As soon as you access the instance and the type is initialized, it will remain in memory for the entire life of your ApplicationDomain. So use it as a normal class and the rest is done on first use.

Upvotes: 1

White Dragon
White Dragon

Reputation: 1267

Perhaps you are over-complicating the issue? i'm not sure why you need to use the cache. Could you not just add a file to the App_Code folder to house your class e.g "mSingleton.cs"

public sealed class mSingleton
{
    static readonly mSingleton _instance = new mSingleton();

    public int MyVal { get; set; }

    public static mSingleton Instance
    {
        get { return _instance; }
    }
    private mSingleton()
    {
        // Initialize members, etc. here.
    }
}

Then it is global to all your code and pages, maintains state until the app pool recycles or there is a app rebuild (i don't know if this causes the app to recycle as well - if it does then it suits your criteria anyway), doesn't need to be added to any cache, application or session variables.. no messy handling

You can do this on page_load in any aspx.cs file and refresh it to see the count go up each time to prove state is maintained:

mSingleton getMyObj = mSingleton.Instance;
getMyObj.MyVal++;

Upvotes: 0

mikey
mikey

Reputation: 5160

I'd not use the cache for this. I'd recommend a static class or singleton with static getInstance().

Upvotes: 0

Related Questions