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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.