Castle DynamicProxy2:在拦截器中获取目标?

时间:2009-05-05 20:01:05

标签: target castle-dynamicproxy iinterceptor

我正在使用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字典中提取“Name”值:

public interface IContrivedExample
{
    string Name { get; }
}

从拦截器中,我想得到“目标”DataContainer,并返回“Name”值:

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");

关于如何获得基础目标的任何想法

注意:这是一个人为的例子,我用来围绕我的问题建立一些背景。

2 个答案:

答案 0 :(得分:2)

我明白了。您必须将代理转换为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];
}

答案 1 :(得分:1)

为什么麻烦?

使用

var container = invocation.InvocationTarget as DataContainer;

BTW,IIUC,您正在尝试实施Castle DictionaryAdapter已经提供的内容。为什么不使用那里已有的东西?