我正在寻找.NET Core中的 RealProxy 替代品,并且此问题将我转发到 DispatchProxy 。
I'm looking for RealProxy replacement in .NET Core, and this issue forwards me to DispatchProxy.
它具有简单的API,但尚不清楚如何将现有的 对象包装到其中代理。 例如,具有以下接口:
It has simple API, but it's unclear, how to wrap existing object into proxy. E.g., having this interface:
interface IFoo { string Bar(int boo); }以及此实现:
class FooImpl : IFoo { public string Bar(int boo) { return $"Value {boo} was passed"; } }如何获得我想要的东西?
how to get what I want?
class Program { static void Main(string[] args) { var fooInstance = new FooImpl(); var proxy = DispatchProxy.Create<IFoo, FooProxy>(); var s = proxy.Bar(123); Console.WriteLine(s); } } class FooProxy : DispatchProxy { protected override object Invoke(MethodInfo targetMethod, object[] args) { return targetMethod.Invoke(/* I need fooInstance here */, args); } }由于 DispatchProxy 后代必须具有无参数构造函数,我唯一的想法就是发明一些方法,例如:
Since DispatchProxy descendants must have parameterless constructor, the only idea I have is to invent some method, like this:
class FooProxy : DispatchProxy { private object target; public void SetTarget(object target) { this.target = target; } protected override object Invoke(MethodInfo targetMethod, object[] args) { return targetMethod.Invoke(target, args); } }并以此方式使用:
var fooInstance = new FooImpl(); var proxy = DispatchProxy.Create<IFoo, FooProxy>(); ((FooProxy)proxy).SetTarget(fooInstance); // the rest of code...这是正确的方法吗?
推荐答案您是正确的,这里除了投射生成的 IFoo之外没有其他选择转换为已知的代理类型( FooProxy ),并在 FooProxy 上使用自定义方法或属性。没有公共API可添加构造函数参数或将代理返回为实现类型。但是, DispatchProxy.Create()将返回 FooProxy 的子类的实例,该子类的类型在运行时通过反射生成
You are right that there is no other option here than to cast the generated IFoo to the known proxy type (FooProxy) and use a custom method or property on FooProxy. There is no public API to add constructor arguments or return the proxy as the implementation type. However, DispatchProxy.Create() will return an instance of a subclass of FooProxy whose type is generated at runtime via reflection and IL emitting.
如果您正在寻找其他快速包装实现并替换接口方法/虚拟方法的方法,建议您改用模拟框架(FakeItEasy,Moq, NSubstitute等。)
If you are looking at other ways to quickly wrap an implementation and replace interface methods / virtual methods, I suggest using mocking frameworks instead (FakeItEasy, Moq, NSubstitute etc.).
更多推荐
如何将现有对象实例包装到DispatchProxy中?
发布评论