Durable Services in Windows Communication Foundation (WCF)

by V.N.S Arun

Read along as we explore the durable services concept in WCF and look at how to implement it by creating an example.


In this article we will learn about durable services and how it can be implemented in Windows Communication Foundation (WCF). I will also demonstrate steps to create a durable service in WCF along with the source code. WCF durable service concept was only introduced in .NET Framework 3.5 version. After reading through this article you should be having a good idea on WCF durable services, how it works and how to build it.

What is a Durable Service in Windows Communication Foundation (WCF)?

Generally web applications, web services and WCF services are stateless. In other words one can say HTTP is a stateless protocol. The word stateless here denotes that a state of the object in WCF service will not be persisted between multiple requests to the service. WCF durable service paves way for building long running applications with a persisted state. WCF durable service helps in persisting the state of the service instance between multiple requests or even if the service/client application is restarted.

This state persistence is done by XML serializing the instance of the server object and storing them in the database with a GUID as a unique key for the record. This GUID will be sent to the service by the client so that the service would retrieve the corresponding instance from the database for that request. Hence the state is persisted. WCF durable service also provides an option to remove the instance from the database.

How it is Different From Sessions in WCF?

As a reader you will be definitely dubious about the fact that what makes the durable service state persistence different from the session state persistence in WCF using the InstanceContextMode.PerSession option. The answer is simple, session state persistence in WCF will only be effective till the client or WCF service is restarted. Once the service or client is restarted the persisted state will be lost as the storage of session is in-memory. On the other hand with WCF durable service state persistence is not based on the user context rather it is based on the GUID passed by the client. Here the state will be persisted even if the client or WCF service is restarted since the instance is stored in the database.

Implementing WCF Durable Services: Prerequisites

In this section we will look at the things need to be done or to be noted while developing a WCF durable service. Check out the below points.

  1. Need to have SQLServer express installed on the machine and create a database to store the serialized instance in it.
  2. Go to C:\WINDOWS\Microsoft.NET\Framework\v3.5\SQL\EN path on your file system; fetch the SQL scripts from the files SqlPersistenceProviderLogic.sql and SqlPersistenceProviderSchema.sql. Here is a brief description for the file contents.
    1. SqlPersistenceProviderSchema.sql: This file contains the script for creating the tables and required schema for storing the object instance.
    2. SqlPersistenceProviderLogic.sql: This file contains the stored procedure script for creating the serialized instance in the database, retrieving the instance and deleting the instance.

Sample Application

In this section we will create a sample WCF durable service. I will also be providing the description along with the source code.

  1. As a first step create a solution named WCFDurableServices solution
  2. Add a WCF Service Application to the solution and name it as WCFDurableService.
  3. Add a Console Application to the solution and name it as ClientApplication.

WCF Service

Let us now implement the durable WCF service. Add a ServiceContract named IAccountingService. Below is the source code:

  namespace WcfDurableService
      public interface IAccountingService
          void PersistInstance();
          void AddAmount(long amount);
          long GetTotalAmount();
          void ClearInstance();

There is nothing different with the service contract for developing durable service as you can witness in the above code. Let us now create a .svc file named AccountingService.svc. Inherit the AccountingService class in AccountingService.svc.cs file and implement the same. Below is the code:

  namespace WcfDurableService
      //Attribute require to mark this implementation as a durable service
      public class AccountingService : IAccountingService
          private long _totalAmount;
          #region IAccountingService Members
          //Attribute to decorate the service methods
          public void PersistInstance()
          public void AddAmount(long amount)
              _totalAmount += amount;
          public long GetTotalAmount()
              return _totalAmount;
          public void ClearInstance()

In the above code you will notice the Serializable attribute. It is required since the instance of this implementation class will be XML serialized and stored in the database. Also you could see there are two new attributes decorating the implementation class and the service method.

  1. DurableService: To decorate the implementation class of the durable service.
  2. DurableOperation: To decorate the service method of the durable services. This attribute allows specifying two Boolean properties.

    1. CanCreateInstance: If this property is set to true then the respective method will create and store the instance in the database when called by the client.
    2. CompletesInstance: If this property is set to true then the respective method will delete the instance in the database when called by the client.

DurableService and DurableOperation attribute will be available only after adding the reference to System.WorkflowServices is added to the WCF service application.

Next is the configuration step in the durable service development. Below is the config section that needs to be placed in the Web.Config file of the WCF application.

  		<add name="DurableServiceDbConnectionString" connectionString="ConnectionStringGoesInHere"/>
  			<service behaviorConfiguration="WcfDurableService.Service1Behavior" name="WcfDurableService.AccountingService">
  				<endpoint address="" binding="wsHttpContextBinding" contract="WcfDurableService.IAccountingService">
  				<behavior name="WcfDurableService.Service1Behavior"  >
  					<serviceMetadata httpGetEnabled="true" />
  					<serviceDebug includeExceptionDetailInFaults="true" />
  						<windowsAuthentication allowAnonymousLogons="true" includeWindowsGroups="true" />
  						     type="System.ServiceModel.Persistence.SqlPersistenceProviderFactory, System.WorkflowServices, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

The connection string for the SQL Server Express database has to be provided and under the behavior section persistenceProvider has to be mentioned as shown in the above configuration section. The connection string name to connect to the SQL Express database is also mentioned in the persistenceProvider section.

The binding to be used on the client and WCF service should be wsHttpContextBinding. This binding allows WCF durable service to exchange the instance GUID between the client and server.

Client Application

As a first step in the client application add the service reference and name the proxy as AccountingService. Below is the Main method code. I have implemented in such a way that it will operate on the same instance until and unless you opt to clear it.

  class Program
          static AccountingServiceClient _client;
          static void Main(string[] args)
              _client = new AccountingServiceClient();
              Console.WriteLine("Instance XML persisted to the database!");
              while (true)
                  Console.WriteLine("Do you want to clear the instanse? (Y/N)");
                  string clearInstance = Console.ReadLine();
                  if (clearInstance.ToUpper().Equals("Y"))
                      Console.WriteLine("Instance XML deleted from the database!");
                      Console.WriteLine("Please enter the amount to deposit: ");
                      Console.WriteLine("Total fund available: {0}", _client.GetTotalAmount());

When the instance is created by calling _client.PersitInstance() method go to your SQL server management studio and query the InstanceData table.

Fig 1.0 shows the record created in the DurableServiceDb.

Fig 1.0

Run the application and Fig 1.1 shows the output window.

Fig 1.1

Try restarting the WCF service and you will be surprised to see the persistence of the data happening on the service side. If you need to make the client to be durable as well then you have to set the InstanceId explicitly to the IContextManager on the client.


Hope this article clearly describes about WCF durable services, the way it works and steps involved in developing it. I have also attached the sample application's source code which you can download for your reference. If you have any doubts or concerns regarding the article then please make use of the comments sections.

Happy Reading!

Related Articles

This article was originally published on Monday Nov 8th 2010
Mobile Site | Full Site