My app generates a lot of objects while doing it's thing. Objects are generated as a result of database queries and they are a part of our ORM solution. Programs who use those object usually requests them one by one.
I want to use System.Runtime.Caching but I'm not sure how since I have specific criteria:
Each user can log to a different database. Applicable for all objects.
Databases can have several different company profiles. Applicable for most objects.
Most objects are multilingual.
Some objects are cached only while a database transaction is alive and then dumped upon rollback or commit.
First solution that comes to mind is to generate a complex string key for cache (ie. database+company+language+object primary key value) but I'm not sure if that's the right way. I'm also not sure how to implement transaction wide caching.
Perhaps I would have more control over cache if I used my own implementation. Something like this:
public class DatabaseCache
{
private ConcurrentDictionary<string, ClassCache> m_databases = new ConcurrentDictionary<string, ClassCache>();
public void Add(string database, string className, object item, params string[] itemKeys)
{
}
}
public class ClassCache
{
private ConcurrentDictionary<string, KeyCache> m_cache = new ConcurrentDictionary<string, KeyCache>();
public void Add(string className, object item, params string[] itemKeys)
{
}
}
public class KeyCache
{
private ConcurrentDictionary<string, object> m_cache = new ConcurrentDictionary<string, object>();
public void Add(object item, params string[] itemKeys)
{
}
}
I am using a very similar approach in a CMS and it works pretty well, (in a CMS most objects are read many times and written a few times).
When an update occurs, cached objects are invalidated. In my cache key string, the first parameter is a cache index, which changes when an update occurs.
If you have many updates, every transaction could do two things. Make the changes in the database and then update the objects that are in cache, so that you don't have to invalidate them.
Regarding transaction wide caching, you could keep a list with all the keys of the objects of the transaction.
At the end of the transaction you can loop this list and remove all of these items from the cache.
Another approach is to keep a collection of the objects of the transactions and store the collection object in the cache. With this approach, you only have only the collection object to remove from the cache.