Class library and static variables in asp.net

I have a class library that should encapsulate ORM logic. To avoid some db calls, it should contain some kind of cache or static variables (I want to avoid them). It is used in asp.net and wcf applications. Since this is a class library, I do not want to access the cache or other asp.net-related materials. I also want to avoid static vars due to their application nature.

How do I implement this? What are you doing to achieve this?

EDIT:

To simplify: imagine a class library encapsulating a DAL. He is negotiating with a database. There are several expensive queries inside. Some of them must be retrieved once for each user and stored somewhere, and some of them can be used for each application (also saved to avoid future calls to the database). The fact is that I usually use Cache, but since this is a DAL class library, I want to enable this functionality inside it (and not in asp.net). Hopefully this will become clearer now;)

+3
source share
1 answer

You should use caching:

, ..:

. ( )

( ):

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

Source: https://habr.com/ru/post/1757194/


All Articles