wcfself-hosting

Run WCF ServiceHost with multiple contracts


Running a ServiceHost with a single contract is working fine like this:

servicehost = new ServiceHost(typeof(MyService1));
servicehost.AddServiceEndpoint(typeof(IMyService1), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService1");
servicehost.Open();

Now I'd like to add a second (3rd, 4th, ...) contract. My first guess would be to just add more endpoints like this:

servicehost = new ServiceHost(typeof(MyService1));
servicehost.AddServiceEndpoint(typeof(IMyService1), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService1");
servicehost.AddServiceEndpoint(typeof(IMyService2), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService2");
servicehost.Open();

But of course this does not work, since in the creation of ServiceHost I can either pass MyService1 as parameter or MyService2 - so I can add a lot of endpoints to my service, but all have to use the same contract, since I only can provide one implementation?
I got the feeling I'm missing the point, here. Sure there must be some way to provide an implementation for every endpoint-contract I add, or not?


Solution

  • You need to implement both services (interfaces) in the same class.

    servicehost = new ServiceHost(typeof(WcfEntryPoint));
    servicehost.Open(); 
    
    public class WcfEntryPoint : IMyService1, IMyService2
    {
        #region IMyService1
        #endregion
    
        #region IMyService2
        #endregion
    }
    

    FYI: I frequently use partial classes to make my host class code easier to read:

    // WcfEntryPoint.IMyService1.cs
    public partial class WcfEntryPoint : IMyService1
    {
        // IMyService1 methods
    }
    
    // WcfEntryPoint.IMyService2.cs
    public partial class WcfEntryPoint : IMyService2
    {
        // IMyService2 methods
    }