当前位置:首页>>ASP.NET教程>>Asp.NET综合技巧>>在NHibernate中拦截器(IInterceptor)的使用
在NHibernate中拦截器(IInterceptor)的使用
2009/11/8 13:19:18

在NHibernate中如果想对CRUD进行一些记录日志这样的操作的话,可以使用IInterceptor来达到目的。

其实还有另外一个接口可用:ILifecycle,它大概是这样:

public NHibernate.LifecycleVeto OnUpdate(ISession s){}
public void OnLoad(ISession s, object id){}
public NHibernate.LifecycleVeto OnSave(ISession s){}
public NHibernate.LifecycleVeto OnDelete(ISession s){}

但是你必须在每个实体类上实现该接口,一般我们的系统中都有大量的实体类,所以实现ILifecycle将是一件费力不讨好的事情。而IInterceptor有着和ILifecycle类似的方法:

public int[] FindDirty(object entity, object id,
object[] currentState, object[] previousState, string[]
propertyNames, NHibernate.Type.IType[] types){}
public object Instantiate(Type type, object id){}
public bool OnFlushDirty(object entity, object id, object[]
currentState, object[] previousState, string[] propertyNames,
NHibernate.Type.IType[] types){}
public object IsUnsaved(object entity){}
public bool OnLoad(object entity, object id, object[] state, string[]
propertyNames, NHibernate.Type.IType[] types){}

// Insert New Object之前会触发;Update old Object之前会触发
public bool OnSave(object entity, object id, object[] state, string[] 
propertyNames, NHibernate.Type.IType[] types){}
public void OnDelete(object entity, object id, object[] state, string[]
propertyNames, NHibernate.Type.IType[] types){}

// Update old Object之前会触发; Insert New Object之后会触发
public void PreFlush(System.Collections.ICollection entities){}
public void PostFlush(System.Collections.ICollection entities){}

我们看到IInterceptor有着比ILifecycle更多的方法,而且IInterceptor是针对Session中的每个实体对象的。但是不便的是,我们并不能阻止事件,只能修改对象的状态(object[] state),返回布尔值来影响最终结果。这个比起AOP就显然差得远了,我们看看NHibernate的源代码也能看出这一点。

下面我们看看该怎么用这个IInterceptor:

1、写一个实现IInterceptor接口的类

    /// <summary>

    /// 日志记录类

    /// </summary>

    public class LogInterceptor : IInterceptor

    {

        #region IInterceptor 成员

        …

        public bool OnLoad(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)

        {

            //AddLog(entity,id,state,propertyNames,"加载");

            return false;

        }

 

        public bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)

        {

            //AddLog(entity,id,state,propertyNames,"保存");

            return false;

        }

 

        public void OnDelete(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)

        {

            //AddLog(entity,id,state,propertyNames,"删除");

        }

 

        public void PreFlush(System.Collections.ICollection entities)

        {

            //AddLog(entities,"保存");

        }

        #endregion

 

        private void AddLog(object entity,object entityID,object[] state,string[] pr