![](/img/trans.png)
[英]How far to go overriding methods, properties, … of a base class e.g. .net TreeNode class
[英]Define the base class or base functionality of a dynamic proxy (e.g. Castle, LinFu)
我已經在NHibernate論壇中提出了這個問題,但我認為這更多是一個普遍的問題。 NHibernate使用代理生成器(例如Castle)來創建其代理。
我想做的是擴展生成的代理,以便實現我自己的一些自定義行為(即比較器)。 我需要這樣做是因為以下標准.NET行為無法產生正確的結果:
//object AC is a concrete class
collection.Contains(AC) = true
//object AP is a proxy with the SAME id and therefore represents the same instance as concrete AC
collection.Contains(AP) = false
如果我的比較器是由AP實現的(即執行id的匹配),則collection.Contains(AP)將返回true,就像我期望的那樣,如果代理是隱式的。 (注意:對於那些說NH繼承自您的基類的人,是的,的確如此,但是NH也可以繼承自接口-這就是我們正在做的事情)
我不確定這是否可行或從哪里開始。 這可以在NH使用的任何常見代理生成器中完成嗎?
使用Castle DynamicProxy,您幾乎沒有選擇。
首先是提供IComparer<T>
為一體additionalInterfacesToProxy
創建代理時。 接口將沒有實際的實現,因此您需要提供一個攔截器,而不是調用Proceed
來提供方法的實際邏輯。
或者,您可以提供一個mixin,它實現所需的接口並提供所需的邏輯。 注意,您很可能需要將mixin參考傳遞回代理或其目標。
僅適用於接口代理的第三個選項是設置基類proxyGenerationOptions.BaseClassForInterfaceProxy = typeof(SomethingImplementingComparer);
LinFu.DynamicProxy可以實現這種行為,但是您必須用自己的自定義攔截器替換NHibernate提供的攔截器,該攔截器將其委托回原始攔截器:
var yourProxiedInterfaceInstance = ...
// Get the Interceptor that NHibernate uses
var proxy = (IProxy)yourProxiedInterfaceInstance;
var interceptor = proxy.Interceptor;
// You'll need to create a decorator class around the IInterceptor interface
var yourInterceptor = new SomeCustomInterceptor(interceptor);
// Replace the interceptor here
proxy.Interceptor = yourInterceptor;
對於LinFu來說,這非常容易,因為它生成的每個代理實例都需要一個攔截器。 如果更改攔截器,則可以自動更改代理的行為。 希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.