WCF

WCF Hello World Example

WCF is very popular platform for developing services. In this blog, we’ll create a very basic and simple example of WCF service in just 6 steps. Steps are:

  1. Declare ServiceContract
  2. Declare DataContract
  3. Implement Service
  4. Configure Service
  5. Host Service
  6. Access Client

Declare ServiceContract

Create a new blank Console solution and name the solution as “LibraryServiceSolution”.

LibraryService_WCF_Solution1

Add a new Interface name “ILibraryService” and follow below steps.

  1. Add a reference to “System.ServiceModel” assembly. System.ServiceModel assembly is the base assembly of WCF Service.
  2. Add the “System.ServiceModel” namespace in the namespaces section.
  3. Add the [ServiceContract] attribute above the interface ILibraryService.
  4. Add method signature “Book SearchBook(string bookName)” into the interface.
  5. Add the attribute [OperationContract] on the method.

using System;
using System.ServiceModel;

namespace LibraryServiceSolution
{
    [ServiceContract]
    interface ILibraryService
    {
        [OperationContract]
        Book SearchBook(string bookName);
    }
}

ServiceContract attribute describes that this interface contains the methods signatures of WCF service.

OperationContract attribute describes that this method is included in WCF service and it is accessible to the client. Without OperationContract attribute on method, a client can’t access this service method.

Declare Data Contract

In WCF, data contract is used for serializing custom data types. In the interface, We are returning the custom type “Book” as a result of “SearchBook” method.

Let’s declare the interface of Book custom data type. Create a new class name “Book” and follow below steps:

  1. Add a reference to “System.Runtime.Serialization” assembly.
  2. Add the namespace “System.Runtime.Serialization” to the namespaces section.
  3. Add the [DataContract] attribute above the class “Book”.
  4. Add a new property “ID” of data type int in class “Book”.
  5. Add the attribute [DataMember] to “ID” property.
  6. Add a new property “Name” of data type string in class “Book”.
  7. Add the attribute [DataMember] to “Name” property.

using System;
using System.Runtime.Serialization;

namespace LibraryServiceSolution
{
    [DataContract]
    class Book
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string Name { get; set; }
    }
}

DataContract attribute specifies that this class is used as a parameter or return type in WCF service.

DataMember attribute specifies that this property is part of data contract.

Implement Service

Create a new class name “LibraryService” and follow below steps:

  1. Inherit from interface “ILibraryService”
  2. Implement the method “SearchBook”

using System;
using System.Collections.Generic;

namespace LibraryServiceSolution
{
    class LibraryService : ILibraryService
    {
        private List<Book> books;

        public LibraryService()
        {
            books = new List<Book>();
            for (int i = 0; i < 20; ++i)
            {
                books.Add(new Book { ID = i, Name = "Name " + i });
            }
        }

        public Book SearchBook(string bookName)
        {
            return books.Find(w => w.Name == bookName);
        }
    }
}

Configure Service

Configuring the service is the main step of WCF service. In this step, we define the endpoint of the service and enable the metadata of the service.

An endpoint is the collection of address, binding and contract.

  1. Address defines the location of the service
  2. Binding in simple terms specify the transport protocol of the service.
  3. Contract list the operations of the service which we already defined in the “ILibraryService” interface.

Metadata file is the description of WCF service in XML format. It describes the service endpoints to the client.

Open “App.config” file and add below configuration settings:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="LibraryServiceSolution.LibraryService" behaviorConfiguration="LibraryServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9999/LibraryService" />
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="LibraryServiceSolution.ILibraryService" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="LibraryServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

In line 3, “system.serviceModel” is the parent tag and it’s contains all the configuration of WCF services.

In line 4, “services” tag contains the definitions of all the WCF services names and endpoints.

In line 5, “service” tag contains the definition of the particular service. “name” attribute of the service tag contains the name of the class that implement the [ServiceContract] interface with namespace and “behaviorConfiguration” attribute contains the name of the behavior that exposed metadata that is described in line 16.

In line 6, 7, 8, we define the base addresses of our LibraryService. Base address is the first part of the address and second part of the address we define in the endpoint.

In line 11, we define an endpoint, containing address, binding and contract. Address is blank, so, our final WCF service address is “http://localhost:9999/LibraryService” + “”. That means our service is hosted on address “http://localhost:9999/LibraryService”.

In line 15, 16, and 17, we enable the metadata of our service. Please note the name of the behavior in line 16 and in the value of behaviorConfiguration in line 5 must be same.

Host Service

For hosting the service, we use the “ServiceHost” class. We just need to pass type information of our “LibraryService” service and call the open method.


using System;
using System.ServiceModel;

namespace LibraryServiceSolution
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost server = new ServiceHost(typeof(LibraryService));
            server.Open();

            Console.WriteLine("Your service is started...");
            Console.ReadLine();

            server.Close();
            
        }
    }
}

Close() method of the ServiceHost class will close the WCF service. Just start the console program. You will get below output:

WCF LibraryService Started

If you found any ‘AccessDenied’ error then try to run the program from the permission of adminstrator.

Access Client

Now, it’s time to use the service. For accessing the service at the client side, we must know the WSDL file location of the WCF service. Copy and paste the address of the service address in the configuration file “http://localhost:9999/LibraryService” in the internet explorer.

Just copy the WSDL address from the internet explorer and open a new Console program. Choose the “Add Service Reference” sub-menu from the Project Menu and paste the WSDL file locatiLibraryService_WSDL_Location1on in the Address textbox and click on the Go button and type the namespace as ‘LibraryServiceSolution’ and click on OK button.

LibraryService_AddServiceReference1

Follow below steps:

  1. Add the namespace “ConsoleApplication1.LibraryServiceSolution” in the namespaces section. ‘ConsoleApplication1’ is the namespace of the console and LibraryServiceSolution is the namespace of the WCF service.
  2. Create an instance of “LibraryServiceClient” class.
  3. Call the SearchBook method.
using System;
using ConsoleApplication1.LibraryServiceSolution;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            LibraryServiceClient client = new LibraryServiceClient();
            Book book =  client.SearchBook("Name 12");
            Console.WriteLine("Book ID : " + book.ID);

            Console.ReadLine();
        }
    }
}

We just created our first WCF service. Congratulations 🙂