joydip_kanjilal
Contributor

How to work with a WCF service programmatically

opinion
Feb 18, 20165 mins
Software Development

Explore ways to work with a WCF service programmatically without the service configuration files

WCF (Windows Communication Foundation) is a secure, reliable, and scalable messaging platform for developing services in .Net. In WCF, you have a unified programming model that you can leverage for building scalable, robust services. It enables you to configure your services either using configuration files or by using code, i.e., programmatically using C# or VB.Net.

Configuring a WCF service has been a pain primarily because of the tedious configuration metadata that you would need to specify to get your WCF service up and running. You can configure your WCF service either using the service configuration files (these are xml files) or by writing code. Since there is no support for debugging configuration files, you can configure your service programmatically as well.

Creating a WCF service

To get started, let’s create a new WCF service. To create a new WCF service, follow these steps.

  1. Open Visual Studio IDE
  2. Click on Start -> File -> New -> Project
  3. Select WCF from the list of the project templates displayed
  4. Specify a name for your WCF service project
  5. Click OK to save your WCF service project

To configure a WCF service you can simply define a static method called Configure. This method should be defined in the service implementation class as shown below.

  public class TestService : ITestService

    {

        public static void Configure(ServiceConfiguration config)

        {

            ServiceEndpoint serviceEndpoint = new ServiceEndpoint(new ContractDescription("ITestService"), new BasicHttpBinding(), new EndpointAddress("basic"));

            serviceEndpoint.Behaviors.Add(new IDGCustomEndpointBehavior());

            config.AddServiceEndpoint(serviceEndpoint);

            config.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });

            config.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });

        }

        public string GetMessage()

        {

            return "Hello";

        }

    }

Hosting the WCF service programmatically

The following code listing shows how you can configure a WCF service and start it using BasicHttpBinding. As you can see in the code listing given below, the service has been configured programmatically and then started.

var serviceUrl = "http://localhost:9000/TestService.svc";

ServiceHost serviceHost = null;

            try

            {

                var uri = new Uri(serviceUrl);

                serviceHost = new ServiceHost(typeof (TestService), uri);

                var serviceMetadataBehavior = new ServiceMetadataBehavior();

                serviceHost.Description.Behaviors.Add(serviceMetadataBehavior);

                serviceHost.AddServiceEndpoint(typeof (IMetadataExchange),

                    MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

                var basicHttpBinding = new BasicHttpBinding();

                serviceHost.AddServiceEndpoint(typeof (ITestService), basicHttpBinding, serviceUrl);

                serviceHost.Open();

                Console.WriteLine("Service started... " + serviceUrl);

            }

            catch (Exception ex)

            {

                serviceHost = null;

                Console.WriteLine("Error starting service" + ex.Message);

            }

            finally

            {

             if (serviceHost != null)

               if (!(serviceHost.State == CommunicationState.Closed))

                 serviceHost.Close();

             serviceHost = null;

            }

When you execute the above code listing, the service gets started at the port mentioned in the service url. To verify that the service is working, open a web browser in your system and browse the service’s debug page at https://localhost:9000/TestService.svc

Note that ServiceMetadataBehavior is used to configure the service metadata and other related information. An instance of ServiceMetadataBehavior is added to the Behaviors collection using this code snippet:

serviceHost.Description.Behaviors.Add(serviceMetadataBehavior);

To use the binding of your choice, you should leverage the appropriate binding class, i.e., BasicHttpBinding, NetTcpBinding, etc. Once all service configuration has been defined, you should make a call to the Open method of the ServiceHost instance to start your service.

If you would like to use TcpBinding to host your service, you can use the following code.

        string serviceUrl = "net.tcp://localhost:9000/TestService/";

            ServiceHost serviceHost = null;

            try

            {

                Uri uri = new Uri(serviceUrl);

                serviceHost = new ServiceHost(typeof(TestService), uri);

                NetTcpBinding netTcpBinding = new NetTcpBinding();

                ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();

                serviceHost.Description.Behaviors.Add(serviceMetadataBehavior);

                serviceHost.AddServiceEndpoint(typeof(IMetadataExchange),

                  MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

                serviceHost.AddServiceEndpoint(typeof(ITestService), netTcpBinding, serviceUrl);

                serviceHost.Open();

                Console.WriteLine("Service started... " + serviceUrl);

            }

            catch (Exception ex)

            {

                serviceHost = null;

                Console.WriteLine("Error starting service" + ex.Message);

            }

            finally

            {

                if (serviceHost != null)

                    if (!(serviceHost.State == CommunicationState.Closed))

                     serviceHost.Close();

                serviceHost = null;

            }

If there is any error in starting the service, an exception is thrown and the appropriate message is displayed using the catch block. The finally block has been used to dispose the ServiceHost instance if it is non null.

If your service is REStful, you would need to leverage WSHttpBinding as shown below.

var serviceUrl = "http://localhost:9000/TestService"; ServiceHost serviceHost = null; try { var uri = new Uri(serviceUrl); serviceHost = new ServiceHost(typeof(TestService), uri);

WSHttpBinding wsHttpBinding = new WSHttpBinding(); wsHttpBinding.MaxReceivedMessageSize = 999999; wsHttpBinding.MessageEncoding = WSMessageEncoding.Text;

serviceHost.AddServiceEndpoint(typeof(ITestService), wsHttpBinding, string.Empty);

ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior(); serviceBehavior.HttpGetEnabled = true; serviceHost.Description.Behaviors.Add(serviceBehavior);

serviceHost.Open(); Console.WriteLine("Service started... " + serviceUrl); } catch (Exception ex) { serviceHost = null; Console.WriteLine("Error starting service" + ex.Message); } finally { if (serviceHost != null) if (!(serviceHost.State == CommunicationState.Closed)) serviceHost.Close(); serviceHost = null; }

You should create a channel factory instance before you can invoke the methods of the service. Here’s how you can achieve this.

BasicHttpBinding basicHttpBinding = new BasicHttpBinding();

var serviceUrl = "http://localhost:9000/TestService";

var endpoint = new EndpointAddress(serviceUrl);

var channelFactory  = new ChannelFactory<ITestService>(basicHttpBinding , endpoint);

ITestService service = channelFactory.CreateChannel(endpoint);

If you are using TCP binding, here’s how you can achieve this.

NetTcpBinding netTcpBinding = new NetTcpBinding();

string serviceUrl = "net.tcp://localhost:9000/TestService/";

var endpoint = new EndpointAddress(serviceUrl);

var channelFactory  = new ChannelFactory<ITestService>

(netTcpBinding , endpoint);

ITestService service = channelFactory.CreateChannel(endpoint);

You are now all set to start consuming your service methods.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author