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>()); }
}
}
我想使用以下接口作为接口代理,从 Fields 字典中提取“Name”值:
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");
关于如何获取潜在目标的任何想法
注意:这是一个人为的示例,我用来围绕我的问题建立一些上下文。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想到了。 您必须将代理强制转换为 IProxyTargetAccessor:
I figured it out. You have to cast the Proxy to IProxyTargetAccessor:
为什么这么麻烦?
使用
BTW,IIUC,您正在尝试实现 已经提供的内容Castle DictionaryAdapter。 为什么不使用已有的东西呢?
Why the hassle?
use
BTW, IIUC, you're trying to implement what is already provided by Castle DictionaryAdapter. Why not use what's already out there?