Multiple bindings in self-hosted WCF Service

Even though WCF is now, more than 5 years old but still I see developers struggling with the multiple bindings specially when hosted in a managed console application. In this post, step by step we will learn to create a WCF Service with multiple bindings and host the service in a managed console application. We will do the following tasks in this post,

  • Create a service with the netTCPBinding
  • Host the service in a console application
  • Add wsHttpBinding EndPoint in the service
  • Consume the service in a client

To start with create a project by choosing either WCF Service Application or WCF Service Library from the WCF tab. I am selecting WCF Service Library project template.

clip_image002

Let us create a very simple service contract as follows


using System.ServiceModel;

namespace MultipleBindingSelfHosted
{
   
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        
    }

}


Next let us implement the service as follows:


namespace MultipleBindingSelfHosted
{
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

       
    }
}


By this step we have created the service and implemented it. Compile the solution to make sure that everything is fine in the WCF project.

Now let us go ahead and add a console application in the project. This application will be the host application in which the service will be hosted. Let us follow the given steps:

  1. Create a console application in the project
  2. Add reference of System.ServiceModel
  3. Add reference of WCF project

Next in the App.config file of the console application we need to add service’s Endpoint configurations. Let us start with adding netTCPBinding Endpoint. To add the configuration follow the steps shown as follows:

  1. Add system.serviceModel
  2. Add services in the system.servicxeModel
  3. Add host base address in the host section
  4. Add Endpoint with netTcpBinding
  5. Add Metadata Endpoint for netTcpBinding

These steps can be done as shown below:

 

<system.serviceModel>

    <services>
      <service name="MultipleBindingSelfHosted.Service1" behaviorConfiguration="MultipleBindingSelfHostedBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:9002/MultipleBindingSelfHosted"/>
          </baseAddresses>
        </host>
        <endpoint address="net.tcp://localhost:9002/MultipleBindingSelfHosted"
                  binding="netTcpBinding" 
                  contract="MultipleBindingSelfHosted.IService1"/>
        <endpoint address="mex"
                  binding="mexTcpBinding" 
                  contract="IMetadataExchange"/>
      </service>
    </services>

  </system.serviceModel>


If you notice above we have added a service behaviour. So let us go ahead and configure the behaviour as follows:

 

<behaviors>
      <serviceBehaviors>
        <behavior name="MultipleBindingSelfHostedBehavior">
          <serviceMetadata httpGetEnabled="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

Great, by this step we have added Endpoint with the netTcpBinding. Next let us go ahead and create instance of the service host by passing service definition class in the constructor.


using System;
using System.ServiceModel; 

namespace MultipleBindingSelfHosted.Host
{
    class Program
    {
        static void Main(string[] args)
        {

            ServiceHost host = new ServiceHost(typeof(Service1));
            host.Open();
            Console.Write("Service is up and running");
            Console.WriteLine("To stop service press any key !!! ");
            Console.ReadKey();
            host.Close();

        }
    }
}


Press F5 to run the host application. You should see host application running as expected as follows:clip_image002[6]

Next we will go ahead and add an Endpoint for wsHttpBinding. To do this follows the steps as discussed follows:

  1. Add new base address
  2. Add new Endpoint with wsHttpBinding
  3. Give name to endpoints in case we may want to access separate Endpoint by providing Endpoint name the client

Add new base address as follows:

<add baseAddress="http://localhost:9001/MultipleBindingSelfHosted"/>

Add new Endpoint as follows. If you notice I have given name to the Endpoint as httpendpoint. You are free to give name of your choice.

<endpoint name="httpendpoint" address="http://localhost:9001/MultipleBindingSelfHosted" 
                  binding="wsHttpBinding" 
                  contract="MultipleBindingSelfHosted.IService1"/>


Also make sure that you have given a name to netTcpBinding Endpoint as well. Next let us go ahead and add metadata endpoint for http binding as well.

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

After configuring two Endpoints app.config of host application will look like as follows:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <system.serviceModel>

    <services>
      <service name="MultipleBindingSelfHosted.Service1" behaviorConfiguration="MultipleBindingSelfHostedBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:9002/MultipleBindingSelfHosted"/>
            <add baseAddress="http://localhost:9001/MultipleBindingSelfHosted"/>
          </baseAddresses>
        </host>
        <endpoint address="net.tcp://localhost:9002/MultipleBindingSelfHosted"
                  binding="netTcpBinding" 
                  contract="MultipleBindingSelfHosted.IService1"/>
        <endpoint address="mex"
                  binding="mexTcpBinding" 
                  contract="IMetadataExchange"/>
        <endpoint name="httpendpoint" address="http://localhost:9001/MultipleBindingSelfHosted" 
                  binding="wsHttpBinding" 
                  contract="MultipleBindingSelfHosted.IService1"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MultipleBindingSelfHostedBehavior">
          <serviceMetadata httpGetEnabled="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

  </system.serviceModel>
</configuration>


Once again go ahead and build and run the application. You should able to get host application running as follows:

image

We have successfully created a self-hosted service with multiple Endpoint. Now let us go ahead and create a client to consume the service. In console application, right click and add service reference. If client is in the same solution then use Discover option else copy paste base address from app.config file of the hosted application.

image

And then you can call the service for two Endpoints as follows

// calling service with TCP binding 
            Service1Client tcpproxy = new Service1Client("tcpendpoint");
            var result1 = tcpproxy.GetData(12);
            Console.WriteLine(result1);

            //calling service with HTTP binding 
            Service1Client httpproxy = new Service1Client("httpendpoint");
            var result2 = httpproxy.GetData(12);
            Console.WriteLine(result2);

            Console.ReadKey(true);


In this way you can create the self-hosted WCF service with multiple Endpoints. I hope this post is useful. Happy Coding!

3 responses to “Multiple bindings in self-hosted WCF Service”

  1. […] Multiple bindings in self-hosted WCF Service (Dhananjay Kumar) […]

  2. I got following error {“The type initializer for ‘System.ServiceModel.Diagnostics.TraceUtility’ threw an exception.”}

  3. very nice explanation thanks sir

Leave a comment

Create a website or blog at WordPress.com