using System; using ln.types.collections; namespace ln.types.odb.ng { public class IdentityCache { WeakKeyReferenceDictionary reverseCache = new WeakKeyReferenceDictionary(); WeakValueDictionary forwardCache = new WeakValueDictionary(); public IdentityCache() { } public bool TryGetValue(Guid identity,out object o) { lock (this) { return forwardCache.TryGetValue(identity, out o); } } public bool TryGetValue(Guid identity, out object o, Func instantiator) { lock (this) { if (!TryGetValue(identity, out o)) { o = instantiator(); forwardCache.Add(identity, o); reverseCache.Add(o, identity); } return false; } } public bool TryGetIdentity(object o,out Guid identity) { lock (this) { return reverseCache.TryGetValue(o, out identity); } } public void Ensure(Guid identity,object o) { lock (this) { if (!forwardCache.ContainsKey(identity)) forwardCache.Add(identity, o); if (!reverseCache.ContainsKey(o)) reverseCache.Add(o, identity); } } } }