'Multiple WCF Services implementing same Service Contract interface

Is it possible for multiple wcf services to implement the same service contract interface?

What I want to do is allow for a test service to be interchangeable for the real service, and to specify which service to be used in the configuration file.

For example:

[ServiceContract]
public interface IUselessService  
{  
  [OperationContract]   
  string GetData(int value);   
}  

Test implementation

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

Real class

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


Solution 1:[1]

Yes, it's not only possible, it is explicitly within the design intentions of service contract interfaces.

Solution 2:[2]

If you define IUselessService interface inside a separate assembly and place this in GAC. This assembly should don't implement anything only define IUselessService interface and some other types which use needs as a parameters of IUselessService.

Both TestService and RealService should implement the same IUselessService interface. I mean you should create two additional project for each service, then TestService and RealService will have no type conflicts.

Solution 3:[3]

I was just experimenting with this issue trying to get the 2 code behind cs files to implement the same contract interface and then trying to switch the concrete classes employed by the .svc file that is exposed. This HAS TO BE possible, as if it is not, it defeats the purpose of a class implementing an interface when it cannot facilitate the polymorphic behavior on it.

I found this line of the .svc file:

<%@ ServiceHost Language="C#" Debug="true" Service="Service2" CodeBehind="~/App_Code/Service2.cs" %>

Basically this line switches the concrete classes which implements the same contract interface.

You will have to reference the class name of the concrete class in the Service attribute. You will also have to change the class file name in the CodeBehind attribute as well, but it is really the class in the Service attribute that will make the switch.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Weldon
Solution 2
Solution 3 Gwasshoppa