在 Castle.DynamicProxy 中,初始化后是否可以更改 mixin 值?
我注意到 DynamicProxy 对象可以实现 IChangeProxyTarget 接口,它允许您执行类似 <代码>((IChangeProxyTarget)myProxyObj).ChangeInitationTarget(newTarget)。
有没有办法类似地更改 DynamicProxy 对象上的 mixin 实现?显然,这比以我没有充分考虑的方式改变目标更复杂和微妙(由于不同的接口实现、混合的多样性等),但这个概念并非完全不可想象。
或者缺乏这一点,有什么关于以相当高性能的方式实现这一目标的想法吗?我有一些关于破解这个的理论想法,但它看起来非常非常复杂:
- 使用
Action
属性 - 在创建 DP 对象时混合此实例 `MixinSwitcher mixinSwitcher = new MixinSwitcher(); proxyGenerationOptions.AddMixinInstance(mixinSwitcher);
- 创建 DP 对象
var dpObj = proxyGenerator.Create...
- 确保将 IMixinSwitcher 添加到接口中以实现 - 使用反射从
dpObj.Gettype()
查找相关 mixin MemberInfo code> - 使用 System.Reflection.Emit 生成此属性的快速设置器。
- 设置 mixinSwitcher.DoSwitch = (SRE setter 方法在这里)
- ((IMixinSwitcher)dpObj).DoSwitch(dpObj, newMixinValue)
- 利润...还是大脑融化?
步骤 1 类可以通用化,以使其能够针对特定/多个实现;缓存步骤 4-5 以提高性能,并且可以清理一般步骤 1 的实现。
即便如此,我也不否认这很疯狂——有更好的方法吗?
I noticed that DynamicProxy objects can implement an IChangeProxyTarget interface, which allows you to do something like ((IChangeProxyTarget)myProxyObj).ChangeInvocationTarget(newTarget)
.
Is there a way to similarly change the mixin implementation on a DynamicProxy object? Obviously this is more complex and nuanced than changing the target in ways I have not fully thought through (due to varying interface implementations, multiplicity of mixins etc) but the concept is not entirely inconceivable.
Or lacking that, any ideas with regards achieving this, in a reasonably performant fashion? I have some theoretical ideas regarding hacking this in but it seems extremely, extremely convoluted:
- Define a MixinSwitcher class (and accompanying IMixinSwitcher interface) with
Action<object, object> DoSwitch
property - Mix an instance of this in when creating DP object `MixinSwitcher mixinSwitcher = new MixinSwitcher(); proxyGenerationOptions.AddMixinInstance(mixinSwitcher);
- Create DP object
var dpObj = proxyGenerator.Create...
- ensure that IMixinSwitcher is added to the interfaces to implement - Use reflection on to find the relevant mixin MemberInfo from
dpObj.Gettype()
- Use System.Reflection.Emit to generate a fast setter for this property.
- Set
mixinSwitcher.DoSwitch = (SRE setter method here)
- ((IMixinSwitcher)dpObj).DoSwitch(dpObj, newMixinValue)
- Profit... or brain melt?
The step 1 class can be genericised to allow it to target specific/multiple implementations; steps 4-5 cached for extra performance, and the general step 1 implementation could be cleaned up.
Even so I don't deny it is pretty mad - is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这不受支持,主要是因为没有人想出一个有用的好方案。你的场景是什么。为什么你希望能够交换 mixin 目标?
No, that's not supported, mostly because no one came up with a good scenario where that would be useful. What is your scenario. Why do you want to be able to swap mixin targets?