Search code examples
c#wcfwcf-hosting

Hosting multiple WCF ServiceContract implementations from a single service


I have a interface and for the same interface i have multiple implementation. so i would like to ask you that how do i expose the endpoint, using one host?

SERVICE CODE

[ServiceContract]
public interface ICalculator
{
    [OperationContract]
    int Add(int num1, int num2);
}
public class Calculator : ICalculator
{
    public int Add(int num1, int num2)
    {
        return num1 + num2;
    }
}
public class Calculator_Fake : ICalculator
{
    public int Add(int num1, int num2)
    {
        return num1 + num1;
    }
}

HOST CODE

class Program
{
    static void Main(string[] args)
    {

        ServiceHost host = new ServiceHost(typeof(WCF_Service.CalService));
        host.Open();
        Console.ReadLine();
    }
}

Host Config

<endpoint address="http://localhost:8000/CalService"
          binding="basicHttpBinding"
          contract="WCF_Service.ICalculator" />

Solution

  • Although you don't say it I am assuming that you want to be able to host both the fake and the real service in a single applcation. If so you can host more than one WCF service in a single application. In order to do so you will need to change the code so that it creates more than one host.

    Code change

    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host1 = new ServiceHost(typeof(Calculator));
            host1.Open();
    
            ServiceHost host2 = new ServiceHost(typeof(Calculator_Fake));
            host2.Open();
    
            Console.ReadLine();
        }
    }
    

    Config change

    <endpoint address="http://localhost:8000/CalService"
              binding="basicHttpBinding"
              contract="WCF_Service.ICalculator" />
    
    <endpoint address="http://localhost:8000/FakeCalService"
              binding="basicHttpBinding"
              contract="WCF_Service.ICalculator" />