Using语句,没有具体的实现

本文关键字:实现 语句 Using | 更新日期: 2023-09-27 18:18:18

我有一个类继承自WebClient -在一些代码中,我试图测试有通常:

using(var client = new SomeWebClient()){...}

现在我不想在测试中使用SomeWebClient类,所以我想注入一些存根。

如果不使用servicelocator模式,我有什么选择?我不能使用任何真正的IoC,因为这个程序集被多个平台使用,包括移动平台和完整的。net

我确信答案就在我眼前,但我想我正在经历"那些日子中的一天"!

Using语句,没有具体的实现

1)使用一个接口

using(ISomeWebClientc = new SomeWebClient()){...}

2a)创建一个工厂,返回一个ISomeWebClient实现。

3)让它在生产代码中返回正确的类,或者让它在测试中创建一个存根。

2b)或者,只需将ISomeWebClient传递给您的类或方法,并在测试或生产代码中对其进行不同的初始化。

可以注射Func<TResult>。然后在using语句中调用此Func,如下所示:

using (ISomeClient client = InjectedFunc())
{
    ...
}
public delegate Func<ISomeClient> InjectedFunc();
...

然后在代码的某个地方,你给这个Func分配一个值,这是一个稍后执行的代码块:

InjectedFunc = delegate(){ return new MyImplementation(); };
// or some other way of creating a new instance, as long as
// you return a fresh one

所以,这在功能上就像你的using块会说:

using (ISomeClient client = new MyImplementation())
{
    ...
}