100 lines
2.9 KiB
C#
100 lines
2.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using oodb.descriptor;
|
|
using System.Dynamic;
|
|
namespace oodb.persistence
|
|
{
|
|
public class PersistenceCache
|
|
{
|
|
public OODB OODB { get; }
|
|
|
|
|
|
Dictionary<Type, TypeCache> typeCaches = new Dictionary<Type, TypeCache>();
|
|
|
|
|
|
public PersistenceCache(OODB oodb)
|
|
{
|
|
OODB = oodb;
|
|
}
|
|
|
|
private TypeCache GetTypeCache(Type type)
|
|
{
|
|
if (!typeCaches.ContainsKey(type))
|
|
typeCaches[type] = new TypeCache(this,type);
|
|
return typeCaches[type];
|
|
}
|
|
|
|
public Persistent Get(Type type,Guid persistenceID)
|
|
{
|
|
return GetTypeCache(type).Get(persistenceID);
|
|
}
|
|
|
|
public void Touch(Persistent persistent)
|
|
{
|
|
GetTypeCache(persistent.GetType()).Touch(persistent);
|
|
}
|
|
|
|
public void Remove(Persistent persistent)
|
|
{
|
|
GetTypeCache(persistent.GetType()).Remove(persistent);
|
|
}
|
|
|
|
|
|
|
|
class TypeCache
|
|
{
|
|
PersistenceCache PersistenceCache { get; }
|
|
TypeCache BaseCache { get; }
|
|
|
|
Type CacheType { get; }
|
|
|
|
Descriptor Descriptor { get; }
|
|
|
|
Dictionary<Guid, WeakReference> cache = new Dictionary<Guid, WeakReference>();
|
|
|
|
public TypeCache(PersistenceCache persistenceCache,Type type)
|
|
{
|
|
PersistenceCache = persistenceCache;
|
|
CacheType = type;
|
|
Descriptor = persistenceCache.OODB.GetDescriptor(type);
|
|
|
|
if (Descriptor.BaseDescriptor != null)
|
|
BaseCache = persistenceCache.GetTypeCache(Descriptor.BaseDescriptor.NativeType);
|
|
}
|
|
|
|
public Persistent Get(Guid persistenceID)
|
|
{
|
|
WeakReference weakReference = cache[persistenceID];
|
|
if (!weakReference.IsAlive)
|
|
{
|
|
Remove(persistenceID);
|
|
throw new KeyNotFoundException(persistenceID.ToString());
|
|
}
|
|
return weakReference.Target as Persistent;
|
|
}
|
|
|
|
public void Touch(Persistent persistent)
|
|
{
|
|
cache[persistent.PersistenceID] = new WeakReference(persistent);
|
|
if (Descriptor.BaseDescriptor != null)
|
|
PersistenceCache.GetTypeCache(Descriptor.BaseDescriptor.NativeType).Touch(persistent);
|
|
}
|
|
|
|
public void Remove(Persistent persistent)
|
|
{
|
|
Remove(persistent.PersistenceID);
|
|
}
|
|
public void Remove(Guid persistenceID)
|
|
{
|
|
cache.Remove(persistenceID);
|
|
if (Descriptor.BaseDescriptor != null)
|
|
{
|
|
PersistenceCache.GetTypeCache(Descriptor.BaseDescriptor.NativeType).Remove(persistenceID);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
}
|