Search code examples
targetcastle-dynamicproxyiinterceptor

Castle DynamicProxy2: Get the Target inside an Interceptor?


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.


Solution

  • I figured it out. You have to cast the Proxy to 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];
    }