Castle DynamicProxy2: ¿Obtener el objetivo dentro de un interceptor?
-
05-07-2019 - |
Pregunta
Estoy usando Castle DynamicProxy2 para " añadir a " interfaces para recuperar campos de un diccionario. Por ejemplo, dada la siguiente clase:
public class DataContainer : IDataContainer
{
private Dictionary<string, object> _Fields = null;
public Dictionary<string, object> Data
{
get { return _Fields ?? (_Fields = new Dictionary<string, object>()); }
}
}
Quiero usar la siguiente interfaz como un proxy de interfaz para extraer " Nombre " valor fuera del diccionario de campos:
public interface IContrivedExample
{
string Name { get; }
}
Desde un interceptor, quiero obtener el " target " DataContainer y devuelve el " Nombre " valor:
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");
Cualquier idea sobre cómo obtener el objetivo subyacente
Nota: este es un ejemplo artificial que estoy usando para establecer un contexto en torno a la pregunta que tengo.
Solución
Lo descubrí. Tienes que lanzar el 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];
}
Otros consejos
¿Por qué la molestia?
uso
var container = invocation.InvocationTarget as DataContainer;
Por cierto, IIUC, estás intentando implementar lo que ya proporciona Castle DictionaryAdapter . ¿Por qué no usar lo que ya existe?