我在服务中引用自动生成的 WCF 客户端。
//Autogenerated Service client
public partial class ServiceClient :
System.ServiceModel.ClientBase<IService>, IService
{
//...
}
//Autogenerated Interface Client
public interface IService {
//...
}
通过以下方式:
public MyService{
public IExternalWsClientFactory ExternalWsClientFactory {get; set; }
public void MyMethod(){
using (var wsCliente = ExternalWsClientFactory.ServiceClient())
{
//...
}
}
}
public class ExternalWsClientFactory : IExternalWsClientFactory
{
public ServiceClient ServiceClient()
{
var wsClient = new ServiceClient();
return wsClient;
}
}
我引用该实现是因为我想使用using
语句 在代码块的末尾处理资源。并且因为 IDisposable
在 ClientBase
下并且接口(interface)不是局部的。
我的问题是我想模拟 ServiceClient
(我已经模拟了 External WsClientFactory
)但是因为我使用了实现,所以我很难做到这个。
注意:实现中自动生成的方法ServiceClient
不是virtual
。
最佳答案
该类是部分的。界面不是。
创建您自己的派生自原始接口(interface)的接口(interface),并使用 IDisposable
对其进行扩展。
public interface IServiceClient: ICommunicationObject, IService, IDisposable { }
使用自定义接口(interface)扩展分部类
public partial class ServiceClient : IServiceClient { }
现在您应该可以通过 using
语句使用您的扩展接口(interface)
public class ExternalWsClientFactory : IExternalWsClientFactory {
public IServiceClient ServiceClient() {
var wsClient = new ServiceClient();
return wsClient;
}
}
关于c# - 单元测试服务和模拟自动生成的 WCF 客户端代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962863/