NHibernate的Proxy如何用Cache
April 1, 2010 at 6:44 am | Posted in Uncategorized | 1 Comment目的:系统中有些数据不大会变化,例如人员信息,但又不想EagerLoad,想采用系统内缓存数据。如何控制Proxy的动作?
方法:1. 继承一个IProxyFactoryFactory,生成自定义的IProxyFactory。
public class ProxyFactoryFactory : IProxyFactoryFactory
{
public IProxyFactory BuildProxyFactory()
{
return new ProxyFactory();
}
public IProxyValidator ProxyValidator
{
get
{
return new DynProxyTypeValidator();
}
}
}
2. 写自定义IProxyFactory
public class ProxyFactory : AbstractProxyFactory
{
private static readonly LinFu.DynamicProxy.ProxyFactory factory = new LinFu.DynamicProxy.ProxyFactory();
protected static readonly ILog log = LogManager.GetLogger(typeof(NHibernate.ByteCode.LinFu.ProxyFactory));
public override INHibernateProxy GetProxy(object id, ISessionImplementor session)
{
INHibernateProxy proxy;
try
{
NHibernate.ByteCode.LinFu.LazyInitializer interceptor = new NHibernate.ByteCode.LinFu.LazyInitializer(this.EntityName, this.PersistentClass, id, this.GetIdentifierMethod, this.SetIdentifierMethod, this.ComponentIdType, session);
object obj2 = base.IsClassProxy ? factory.CreateProxy(this.PersistentClass, interceptor, this.Interfaces) : factory.CreateProxy(this.Interfaces[0], interceptor, this.Interfaces);
proxy = (INHibernateProxy)obj2;
object target = TryGetCachedTarget(this.PersistentClass, id);
if (target != null)
{
interceptor.SetImplementation(target);
}
}
catch (Exception exception)
{
log.Error("Creating a proxy instance failed", exception);
throw new HibernateException("Creating a proxy instance failed", exception);
}
return proxy;
}
private object TryGetCachedTarget(Type persistentClass, object id)
{
//return buffered entity
}
}
这里采用LinFu的LazyInitializer,首先尝试读系统缓存,如果没用,用原有LazyInitializer,如果有,则用缓存内内容,然后设置好LazyInitializer的target。
1 Comment »
RSS feed for comments on this post. TrackBack URI
Leave a Reply
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.