【问题标题】:Castle DynamicProxy2: Get the Target inside an Interceptor?Castle DynamicProxy2:在拦截器中获取目标?
【发布时间】:2010-10-24 00:34:00
【问题描述】:

我正在使用 Castle DynamicProxy2 来“附加”接口以从字典中检索字段。例如,给定以下类:

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

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

我想使用以下接口作为接口代理,从 Fields 字典中提取“名称”值:

public interface IContrivedExample
{
    string Name { get; }
}

我想从拦截器中获取“目标”DataContainer,并返回“名称”值:

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

关于如何获得潜在目标的任何想法

注意:这是一个人为的例子,我用来围绕我的问题建立一些背景。

【问题讨论】:

    标签: target castle-dynamicproxy iinterceptor


    【解决方案1】:

    我想通了。您必须将代理转换为 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];
    }
    

    【讨论】:

      【解决方案2】:

      为什么这么麻烦?

      使用

      var container = invocation.InvocationTarget as DataContainer;
      

      顺便说一句,IIUC,您正在尝试实现Castle DictionaryAdapter 已经提供的功能。为什么不使用已经存在的东西?

      【讨论】:

      • 最初,我尝试将 InvocationTarget 转换为 DataContainer,但没有成功。这就是导致我使用 IProxyTargetAccessor 的原因。至于 DictionaryAdapter 1)我不知道它存在 2)我在“DataContainer”上还有其他属性,而不仅仅是字段。我省略了这一点,因为它与我所问的问题无关。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 2012-03-31
      • 2015-10-09
      • 1970-01-01
      • 2011-02-09
      • 2011-08-04
      • 1970-01-01
      相关资源
      最近更新 更多