views:

72

answers:

1

I have class library which should encapsulates orm logic. To avoid some db calls, it should contain some kind of cache or static variables (I want to avoid them). It's used in asp.net and wcf applications. Since it's class library, I don't want to access Cache or other asp.net related stuff. I also want to avoid static vars because of the application scope nature of them.

How should I implement that? What do you do to achieve this?

EDIT:

To simplify: imagine class library encapsulating DAL. It talks to database. There are some costly queries inside. Some of them should be fetched once per user and stored somewhere and some of them could be used per Application (also stored to avoid future calls to DB). The thing is that normally I would use Cache, but since it's DAL class library, I want to include this functionality inside it (not in asp.net). Hope it's more clear now ;)

+2  A: 

You should use caching:

Use Patterns, Interfaces etc:

Your class library should be loosely coupled. (Easy to exchange and no cross references)

Example (how I'm doing it simplified):

namespace MyDbContext
{
    var cache;
    var db;

    public MyDbContext()
    {
        // Cache init
        cache = ....;

        // DB init (can be factory or singleton)
        db = DataBase.Instance();
    }

    public class Car
    {
        // Db tuple id
        public CarId { get; set; }

        public Car(int id)
        {
             CarId = id;
        }

        public Car GetFromDb()
        {
            // your db code will be here
            Car myCar = ....;

            // cache your object
            cache.Put("Car" + CarId.ToString(), myCar);
            return myCar;
        }

        public Car Get()
        {
            // try to get it from cache or load from db
            Car mycar = cache.Get("Car" + CarId.ToString()) as Car ?? GetFromDb();
        }

        public ClearCache()
        {
            cache.Put("Car" + CarId.ToString(), null);
            // maybe cache.Remove("Car" + CarId.ToString())
        }
    }
}
Andreas Rehm
?:) some commas, to make it readable?
StupidDeveloper
Wallace Breza
Yes - its now AppFabric - you can find more information here:http://msdn.microsoft.com/en-us/windowsserver/ee695849.aspx
Andreas Rehm
Sorry, but I asked about alternative to statics that can be used INSIDE of class library. I don't want to use Asp.net goodies.
StupidDeveloper
You should have a look on Patterns...
Andreas Rehm
Andreas, I have. Why do you keep repeating it? Can you give me concrete example of what can be used from Patterns that will help me solve this problem?
StupidDeveloper
It depends - but I would use a factory pattern.
Andreas Rehm
Factory? What that has in common with statics in class library (or caching) ?
StupidDeveloper