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?