攔截器的方法OnLoad
[TestFixture]
public class InterceptorTest : NhibernateSessionHelper
{
[Test]
public void GetEntiy()
{
//ok trigger OnLoad in the Interceptor
var user = GetSession().Get<User>(1);
Assert.IsNotNull(user);
}
[Test]
public void GetProjection()
{
var crit = GetSession().CreateCriteria<User>();
crit.Add(Restrictions.Eq("Id", 5));
crit.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("Id"), "Id")
.Add(Projections.Property("Username"), "UserName"));
crit.SetResultTransformer(Transformers.AliasToBean(typeof(LightweightUser)));
//does not trigger the Interceptor
var result = crit.List<LightweightUser>();
Assert.IsNotNull(result.First());
}
}
//Wire the Sessionfactory with Interceptor
private static ISessionFactory CreateSessionFactory()
{
return new Configuration()
.CurrentSessionContext<ThreadStaticSessionContext>()
.SetInterceptor(new MyInterceptor())
.Configure().BuildSessionFactory();
}
public class MyInterceptor: IInterceptor
{
public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
{
//do stuff
var s = entity;
return base.OnLoad(entity, id, state, propertyNames, types);
}
由於僅在PreLoadEvent處理調用。這是在兩種情況下引發的:從數據庫加載實體時,或者從緩存組裝實體時。使用像您這樣的投影創建的對象不被視爲實體。
如果要應用相同的代碼爲實體和LightweightUser的元組可以實現您的自定義IResultTransformer含
Transformers.AliasToBean(typeof(LightweightUser))
,並要求原變壓器方法後一個實例應用您的
邏輯
//do stuff
如果想了解更多關於攔截器,我建議你閱讀我的博客條目列表這裏開始的:http://blog.scooletz.com/2011/02/03/nhibernate-interceptor-magic-tricks-pt-1/