我做的事情最近被認爲是可怕的,但我個人喜歡這種實驗。這裏有一個電報風格描述:代理NHibernate對象與城堡DynamicProxy燕子NH功能
- 使用NH來獲取數據對象
- 每個數據對象由CastleDynamicProxy包裹
- 當裝飾,帶有自定義屬性屬性進行查詢,重定向到自己的代碼,而不是NHibernate的獲取返回值。
對象創建/取數據代碼
Objects=GetAll().Select(x=>ProxyFactory.CreateProxy<T>(x)).ToList();
public IList<Person> GetAll()
{
ISession session = SessionService.GetSession();
IList<Person> personen = session.CreateCriteria(typeof(Person))
.List<Person>();
return personen;
}
代理生成代碼:
public T CreateProxy<T>(T inputObject)
{
T proxy = (T)_proxyGenerator.CreateClassProxy(typeof(T), new ObjectRelationInterceptor<T>(inputObject));
return proxy;
}
使用的攔截器被定義像這樣:
public class MyInterceptor<T> : IInterceptor
{
private readonly T _wrappedObject;
public MyInterceptor(T wrappedObject)
{
_wrappedObject = wrappedObject;
}
public void Intercept(IInvocation invocation)
{
if (ShouldIntercept(invocation)) { /* Fetch Data from other source*/ }
else
{
invocation.ReturnValue = invocation.Method.Invoke(_wrappedObject, invocation.Arguments);
}
}
public bool ShouldIntercept(IInvocation invocation)
{
// true if Getter/Setter and Property
// has a certain custom attribute
}
}
這工作正常在沒有NHibernate的環境(在cod中創建對象e,對象擁有自己的數據)。 不幸的是,Intercept方法中的else
部分似乎讓NHibernate不起作用,它似乎將_wrappedObject
簡化爲基本類型功能(而不是由NHibernate代理),因此所有映射的Child集合都保留爲空。
我試着從lazy
切換到eager
加載(並確認所有的SQL都被執行),但是根本沒有任何改變。
有沒有人有一個想法,我可以做些什麼來恢復工作?
非常感謝!