简体   繁体   中英

Class library and static variables in asp.net

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 ;)

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())
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM