2009-05-05 33 views
2

我正在使用Castle DynamicProxy2來「添加」接口以從字典中檢索字段。例如,給出下面的類: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>()); } 
    } 
} 

我想用下面的接口作爲接口代理提取「名稱」值從田野詞典:

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

如何讓潛在的目標有什麼想法

注意:這是一個人爲設計的例子,我用它來建立一些關於我所擁有的問題的背景。

回答

2

我想通了。您必須將代理投放到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]; 
} 
1

爲什麼麻煩?

使用

var container = invocation.InvocationTarget as DataContainer; 

BTW,IIUC,你想實現的東西已經被Castle DictionaryAdapter提供。爲什麼不使用已經存在的內容?

+0

最初,我嘗試將InvocationTarget作爲DataContainer進行投射,但沒有奏效。這是什麼導致我使用IProxyTargetAccessor。 至於DictionaryAdapter 1)我不知道它存在和2)我有「DataContainer」其他屬性不只是字段。我忽略了這一點,因爲它與我所問的問題無關。 謝謝! – Jordan 2009-05-14 16:16:23