Den*_*nis 7 .net c# realproxy .net-core
我正在RealProxy.NET Core 中寻找替代品,这个问题将我转发到DispatchProxy.
它有简单的API,但不清楚如何将现有对象包装到代理中。
例如,有这个界面:
interface IFoo
{
string Bar(int boo);
}
Run Code Online (Sandbox Code Playgroud)
和这个实现:
class FooImpl : IFoo
{
public string Bar(int boo)
{
return $"Value {boo} was passed";
}
}
Run Code Online (Sandbox Code Playgroud)
如何得到我想要的?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
由于DispatchProxy后代必须具有无参数构造函数,因此我唯一的想法是发明一些方法,如下所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
并以这种方式使用它:
var fooInstance = new FooImpl();
var proxy = DispatchProxy.Create<IFoo, FooProxy>();
((FooProxy)proxy).SetTarget(fooInstance);
// the rest of code...
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?
您是对的,除了将生成的IFoo转换为已知的代理类型 ( FooProxy) 并在 上使用自定义方法或属性之外,没有其他选择FooProxy。没有公共 API 来添加构造函数参数或将代理作为实现类型返回。但是,DispatchProxy.Create()将返回FooProxy其类型在运行时通过反射和 IL 发射生成的子类的实例。
如果您正在寻找其他方法来快速包装实现并替换接口方法/虚拟方法,我建议改用模拟框架(FakeItEasy、Moq、NSubstitute 等)。
| 归档时间: |
|
| 查看次数: |
4327 次 |
| 最近记录: |