简体   繁体   English

覆盖WCF客户端方法

[英]Override WCF Client Methods

I have a WCF service that I use in one of my applications. 我有一个在我的应用程序中使用的WCF服务。 Everything is working just fine, but I am trying to create some test classes that have the same API, but avoid the trip to the server to get their information. 一切工作都很好,但是我正在尝试创建一些具有相同API的测试类,但要避免去服务器获取信息。 For example: 例如:

// Goes to the server to get a list of names.  It might be a while.
MyClient client = new MyClient();
string[] theNames = client.GetSpitefulUsers();
...

// This is what I would use in a test case...
public FakeClient : MyClient
{
  ...
  public override string[] GetSpitefulUsers()
  {
    // This returns almost immediately, but I can't just override it because the
    // 'MyClient' definition is generated code.
    return new string[] {"Aldo", "Barry", "Cassie"};
  }
}

So what is the easiest way to provide this type of functionality without having to resort to clever hacks, mocking libraries, etc? 那么,无需借助聪明的hack,模拟库等来提供这种功能的最简单方法是什么?

WCF service reference has an interface, so all your logic should refer to that interface, not service client. WCF服务引用具有接口,因此您的所有逻辑都应引用该接口,而不是服务客户端。 In such case, you will be able to choose, what implementation(real or fake) to pass to your application logic. 在这种情况下,您将能够选择将哪种实现方式(真实或伪造)传递给应用程序逻辑。

Let's say your WCF service interface is this: 假设您的WCF服务接口是这样的:

public interface IWcfInterface {
     string[] GetTheNames();
}

And your application logic class looks like: 您的应用程序逻辑类如下所示:

public class ApplicationLogic {

     public IWcfInterface WcfInterface {get;set;}

     public SomeLogic() {
         WcfInterface.GetTheNames();
     } 
}

So in case you need real implementation, you just pass it to WcfInterface property of your application logic (usually this does dependency injection container). 因此,如果您需要真正的实现,只需将其传递给应用程序逻辑的WcfInterface属性(通常这样做就是依赖注入容器)。

Fake implementation will also look simple: 伪实现也看起来很简单:

public FakeImplementation : IWcfInterface {
     public string[] GetTheNames() {
         return new string[] { "foo", "bar" };
     }
}

if i am right the compiler will suggest to use the keyword new instead. 如果我是正确的,编译器会建议使用关键字new。

http://msdn.microsoft.com/en-us/library/435f1dw2.aspx http://msdn.microsoft.com/en-us/library/435f1dw2.aspx

This msdnpage will explain how to use it. 此msdnpage将解释如何使用它。

public class BaseC
{
    public int x;
    public void Invoke() { }
}
public class DerivedC : BaseC
{
    new public void Invoke() { }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM