ETFairfax
ETFairfax

Reputation: 3814

Caching ideas anyone?

I have the following, very interesting class ...

pubilc class Thing{

public Thing()
{
    DoSomethingThatTakesALongTime();
}

public boolean CheckSomething(string criteria)
{
    return  criteria == "something";
} }

In my ASP.Net MVC application, I need to make a call to CheckSomething very frequently.

As you can see, the constructor takes a long time to load.

What approaches can I use to cache the class? Keep in mind that I want to keep it testable ... and I don't know what that entails!!!!

Cheers,

ETFairfax

Upvotes: 0

Views: 193

Answers (3)

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65391

You could use the Factory Pattern to create it (Flyweight pattern to share memory)

Create a Factory that returns an instance of the class. The factory would look like this

if instance in cache

  • return cached instance

if not

  • create instance
  • cache instance
  • return instance

For cache you could use HttpContext Cache or Enterprise Library Cache.

EDIT

Interesting discussion below of which pattern this is.

My understanding is as follows:

  • I ask something to create the object, that something is a factory, therefore factory pattern.
  • I try to reuse an object in memory, flyweight pattern. The python code in this example looks very much like my answer: http://en.wikipedia.org/wiki/Flyweight_pattern
  • But there is only a single instance of the object, therefore the singleton pattern
  • The cache where the object is stored is also a singleton

Upvotes: 2

Drevak
Drevak

Reputation: 867

if your thing class does something global to your aplication (not session dependant) just make the class static or add the instance to the cache (HttpContext.Cache)

Upvotes: 0

user151323
user151323

Reputation:

You can create a static instance of that class.

Somewhere:

public static Thing singleThing = new Thing ();

Now upon the first access of the singleThing variable for a given application domain your constructor will work out. After this is done the object will be kept in memory until the end of the application domain (server restart, update of code, changes in web.config, recycling etc.). It means the once initialized object will be available to all clients of your application.

Upvotes: 2

Related Questions