Castle DynamicProxy2:インターセプター内でターゲットを取得しますか?
-
05-07-2019 - |
質問
Castle DynamicProxy2を使用して、「タックオン」します。辞書からフィールドを取得するインターフェース。たとえば、次のクラスがある場合:
public class DataContainer : IDataContainer
{
private Dictionary<string, object> _Fields = null;
public Dictionary<string, object> Data
{
get { return _Fields ?? (_Fields = new Dictionary<string, object>()); }
}
}
「名前」を抽出するためのインターフェイスプロキシとして次のインターフェイスを使用したいFieldsディクショナリの値:
public interface IContrivedExample
{
string Name { get; }
}
インターセプターから、「ターゲット」を取得したいDataContainer、および&quot; Name&quot;を返します。値:
public void Intercept(IInvocation invocation)
{
object fieldName = omitted; // get field name based on invocation information
DataContainer container = ???; // this is what I'm trying to figure out
invocation.ReturnValue = container.Fields[fieldName];
}
// Somewhere in code
var c = new DataContainer();
c.Fields.Add("Name", "Jordan");
var pg = new ProxyGenerator();
IContrivedExample ice = (IContrivedExample) pg.CreateInterfaceProxyWithTarget(..., c, ...);
Debug.Assert(ice.Name == "Jordan");
基礎となるターゲットを取得する方法についての考え
注:これは、私が持っている質問に関するコンテキストを確立するために使用している不自然な例です。
解決
わかりました。プロキシをIProxyTargetAccessorにキャストする必要があります:
public void Intercept(IInvocation invocation)
{
object fieldName = omitted; // get field name based on invocation information
var accessor = invocation.Proxy as IProxyTargetAccessor;
DataContainer container = (DataContainer) accessor.DynProxyGetTarget();
invocation.ReturnValue = container.Fields[fieldName];
}
他のヒント
面倒な理由
使用
var container = invocation.InvocationTarget as DataContainer;
BTW、IIUC、あなたはすでに Castle DictionaryAdapter 。すでにあるものを使用してみませんか?
所属していません StackOverflow