Over a million developers have joined DZone.

Caching In WCF Services: Part 2 - AppFabric Distributed Cache

DZone's Guide to

Caching In WCF Services: Part 2 - AppFabric Distributed Cache

· ·
Free Resource


A couple of months ago, I wrote an article about caching in WCF using the in-process memory cache available in the .NET 4.0 framework. This component offers a lightweight caching solution that can easily be integrated in various types of .NET applications.

There are scenarios where a more advanced caching solution is required. The standard .NET 4.0 cache cannot be shared among multiple servers. Every server has its own isolated instance of the cache. Furthermore, it shares memory with the application. A 32-bit application can allocate at maximum 4 GB of RAM (on a 64-bit OS; maximum 2GB of RAM on a 32-bit OS). There can be situations where you want that the cache of a 32-bit app is larger than 2 GB (although these situations are rare).


Microsoft offers a distributed cache as part of Windows Server AppFabric. This cache can be installed on Window Server 2008 and higher. It is also available in the cloud on Windows Azure. The AppFabric cache is a distributed out of process cache; this means that the cache can be shared among multiple servers and applications. Because it runs outside the application process, it can survive application shut downs and it can be larger then 4 GB for 32-bit applications.

You can deploy AppFabric in two ways on your network: on every application server hosting your application or as a separate infrastructure layer independent of your application servers. The lather provides more flexibility in terms of being able to scale your caching and application server layers independent of each other, but it comes at a higher cost of servers and an increased latency to access the cache.


Configuring the AppFabric caching server

AppFabric can be download for free from the Microsoft download site. At the moment of writing, the latest version available is AppFabric 1.1. It requires at least Windows Vista or Windows Server 2008. For testing the AppFabric cache, I have setup a Windows Server 2008 R2 VM configured in workgroup modus. I choose to deploy my WCF service, on a separate server.

Prior to the installation of AppFabric, I created a technical user account called “AppFabricCacheUser” that will be used to run the caching service. I also created a network share called “AppFabricCache”. If you would use multiple servers, the same user account must be created on all the servers. These user accounts must have the same password on all servers. Only one server must host a network share for the AppFabric cache. The AppFabric user account must have admin rights on the server hosting the share.

Please note: the configuration of AppFabric is different in case your servers are part of an AD domain. Then you don’t need to setup a network share or separate technical accounts on each server. Most companies should have an AD domain. Please consult the AppFabric MSDN pages for more information. I recommend to only use AppFabric caching in workgroup mode in a sandboxed test environment. Otherwise, always use it in AD mode if possible.

AppFabric consists of two parts, the hosting features and the distributed cache. Because this article is about caching, I only installed the necessary caching features.


After the installation is finished, we must launch the “AppFabric Server Configuration Wizard”. We must specify the Caching Service account we created earlier, the XML Caching Service configuration provider and the file share we created earlier.


After this is done, press “next” to continue to following screen. On this screen, we can change the network ports if needed. I choose to stick with the defaults.


Now this is done, we can start our cache using the PowerShell. In order to do this, launch the “Caching Administration Windows PowerShell” and enter the following command: Start-CacheCluster.

By default, security is enabled on the cache. So we must grant access to our client. Because I run in workgroup modus, I must create an account on my server with the exact same user name and password as will be used by my WCF service on the AppFabric caching client. Granting access to a user account can be done with the following command: Grant-CacheAllowedClientAccount -Account “YourUserAccountName”.

Please note: in case of an AD domain is available, the user account must not be created on the server. It is sufficient that the account is known in AD.


Configuring the AppFabric caching client

On the client, the client at least the “Cache Client” of AppFabric must be installed. No special configuration is required.


Developing the WCF service

For the sake of simplicity, I kept the actual programming code to the strict minimum. The sample WCF application consists of two components: a (slow) repository and a WCF service.

First we must add a reference to two DLL’s installed by the AppFabric installer. They can be found in the installation folder of AppFabric.


The slow repository is called: SlowRepository (very creative naming; I know…)

public class SlowRepository
    public IEnumerable<string> GetPizzas()

        return new List<string>() { "Hawaii", "Pepperoni", "Bolognaise" };

I kept the WCF service very basic. It creates an instance of the DataCache object inside its constructor. This object offers an interface to the distributed cache. In order to create it, we must provide the addresses and network ports of the servers hosting the distributed cache.

public class PizzaService : IPizzaService
    private const string CacheServerName = "WIN-53K8O7PMTOP";
    private const int CacheServerPort = 22233;
    private const string CacheKey = "availablePizzas";

    private DataCache cache;
    private SlowRepository repository;

    public PizzaService()
        // Setup AppFabric Cache
        List<DataCacheServerEndpoint> servers = new List<DataCacheServerEndpoint>();
        servers.Add(new DataCacheServerEndpoint(CacheServerName, CacheServerPort));

        DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();
        configuration.Servers = servers;

        //Set default properties for local cache (local cache disabled)
        configuration.LocalCacheProperties = new DataCacheLocalCacheProperties();
        configuration.SecurityProperties = 
            new DataCacheSecurity(DataCacheSecurityMode.None, DataCacheProtectionLevel.None);

        DataCacheFactory cacheFactory = new DataCacheFactory(configuration);
        this.cache = cacheFactory.GetCache("default"); // Get the default cache

        // Create our 'slow' repository
        this.repository = new SlowRepository();

    public IEnumerable<string> GetAvailablePizzas()
        IEnumerable<string> availablePizzas = null;

        // Try to get the item from the cache
        availablePizzas = (IEnumerable<string>)cache.Get(CacheKey);

        if (availablePizzas != null)
            return availablePizzas;
            availablePizzas = repository.GetPizzas();

            // Store data in the cache
            cache.Put(CacheKey, availablePizzas);

            return availablePizzas;

If you call the service twice, you will notice that the second time the data is taken from the cache instead of from the repository. If we restart the web service, the data is still taken from the cache. If we execute the PowerShell command “Get-CacheStatistics” we can see that the cache contains our data.



Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}