多个WCF服务实现相同的服务合同接口

And*_* Wu 5 .net wcf interface

多个wcf服务是否可以实现相同的服务契约接口?

我想要做的是允许测试服务可以与实际服务互换,并指定在配置文件中使用哪个服务.

例如:

[ServiceContract]
public interface IUselessService  
{  
  [OperationContract]   
  string GetData(int value);   
}  
Run Code Online (Sandbox Code Playgroud)

测试实施

public class TestService : IUselessService  
{  
  public string GetData(int value)  
  {  
    return "This is a test";   
  }  
}  
Run Code Online (Sandbox Code Playgroud)

真正的课程

public class RealService : IUselessService  
{  
  public string GetData(int value)  
  {  
    return string.Format("You entered: {0}", value);  
  }  
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*don 5

是的,它不仅可能,它明确地属于服务合同接口的设计意图.

  • 为了能够使用相同的接口,接口不仅必须具有相同的签名(相同的参数).它在.NET类型系统中必须相同.为此,必须将接口的定义放在强签名程序集中,并使用GACUtil -i MyInterface.dll放置在GAC中.然后在两个项目中都必须引用这个程序集. (2认同)

And*_* Wu 5

谢谢你的回答.我现在有一个适用于我的解决方案,无需将接口放在单独的程序集和GAC中.我不是在为其他项目使用接口,只是在同一个项目中为多个服务使用相同的接口.

我试图做的是在WCF服务的配置文件中进行RealService和TestService之间的更改,因此客户端不会知道差异(客户端不必更改其配置以指向不同的.svc文件) .我不确定这是可能的,或者如果它是最不可能的,它绝对不是直截了当的.

我现在正在做的只是在WCF服务的配置文件中指定两个服务,然后根据我想要的服务将客户端指向一个或另一个.由于此WCF服务仅供内部使用,并且我们可以控制客户端和服务,因此这不是一个糟糕的权衡.无论如何,这个解决方案的意图可能更明确.

这是配置文件的片段:

<services>
      <service behaviorConfiguration="WcfService1.Service1Behavior"
               name="WcfService1.TestService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="testBasicHttpBinding" 
          contract="WcfService1.IUselessService">              
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
      <service behaviorConfiguration="WcfService1.Service1Behavior"
               name="WcfService1.RealService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="testBasicHttpBinding"
         contract="WcfService1.IUselessService">             
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
Run Code Online (Sandbox Code Playgroud)