2

I'm using Castle DynamicProxy2 to "tack on" interfaces to retrieve fields from a dictionary. For example, given the following class:

public class DataContainer : IDataContainer
{
    private Dictionary<string, object> _Fields = null;

    public Dictionary<string, object> Data
    {
        get { return _Fields ?? (_Fields = new Dictionary<string, object>()); }
    }
}

I want to use the following interface as an interface proxy to extract the "Name" value out of the Fields dictionary:

public interface IContrivedExample
{
    string Name { get; }
}

From an interceptor, I want to get the "target" DataContainer, and return the "Name" value:

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

Any thoughts on how to get the underlying target

Note: this is a contrived example I'm using to establish some context around the question I have.

4

2 回答 2

3

我想到了。您必须将代理转换为 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];
}
于 2009-05-05T20:12:22.567 回答
1

为什么麻烦?

利用

var container = invocation.InvocationTarget as DataContainer;

顺便说一句,IIUC,您正在尝试实现Castle DictionaryAdapter已经提供的功能。为什么不使用已经存在的东西?

于 2009-05-13T10:45:57.487 回答