views:

470

answers:

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.

A: 

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];
}
Jordan
A: 

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?

Krzysztof Koźmic
Initially, I tried casting the InvocationTarget as a DataContainer and that did not work. That is what lead me to using IProxyTargetAccessor.As for the DictionaryAdapter 1) I didn't know it existed and 2) I have other properties on the "DataContainer" than just Fields. I ommited that because it wasn't relevant to the question I was asking.Thanks!
Jordan