Question

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.

Was it helpful?

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];
}

OTHER TIPS

Why the hassle?

use

var container = invocation.InvocationTarget as DataContainer;

BTW, IIUC, you're trying to implement what is already provided by Castle DictionaryAdapter. Why not use what's already out there?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top