Domanda

Sto usando Castle DynamicProxy2 per " virare su " interfacce per recuperare campi da un dizionario. Ad esempio, data la seguente classe:

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

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

Voglio usare la seguente interfaccia come proxy di interfaccia per estrarre il "Nome" valore fuori dal dizionario Fields:

public interface IContrivedExample
{
    string Name { get; }
}

Da un intercettore, voglio ottenere il "target" DataContainer e restituisci il " Nome " Valore:

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

Qualche idea su come ottenere l'obiettivo sottostante

Nota: questo è un esempio inventivo che sto usando per stabilire un contesto attorno alla domanda che ho.

È stato utile?

Soluzione

L'ho capito. Devi trasmettere il proxy a 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];
}

Altri suggerimenti

Perché la seccatura?

utilizzo

var container = invocation.InvocationTarget as DataContainer;

A proposito, IIUC, stai cercando di implementare ciò che è già fornito da Castle DictionaryAdapter . Perché non usare ciò che è già là fuori?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top