When using Windows Azure AppFabric Caching you will have to configure the caching client to use a provisioned cache. In the past I’ve given examples of doing this using an application configuration file, but there are times where you may want to programmatically configure the caching client. Fortunately, it’s really quite easy and straight forward.

Caching Client Code

  1. // define the cache details

  2. string serviceUrl = “YOURNAMESPACE.cache.appfabriclabs.com”;

  3. string authorizationToken = “YOURTOKEN”;

  4. // declare an array for the cache host

  5. List server = new List();

  6. server.Add(new DataCacheServerEndpoint(serviceUrl, 22233));

  7. // setup the DataCacheFactory configuration

  8. DataCacheFactoryConfiguration conf = new DataCacheFactoryConfiguration();

  9. conf.IsRouting = false;

  10. conf.SecurityProperties = new DataCacheSecurity(authorizationToken);

  11. conf.Servers = server;

  12. conf.RequestTimeout = new TimeSpan(0, 0, 45);

  13. conf.ChannelOpenTimeout = new TimeSpan(0, 0, 45);

  14. // create the DataCacheFactor based on config settings

  15. DataCacheFactory dataCacheFactory = new DataCacheFactory(conf);

  16. // get the default cache client

  17. DataCache dataCache = dataCacheFactory.GetDefaultCache();

  18. // put and retrieve a test object

  19. dataCache.Put(“key”, “1”);

  20. string value = dataCache.Get(“key”) as string;

  21. Console.WriteLine(“Your value: “ + value);

Here are some of the more interesting pieces:

  • Line 6: Create a DataCacheServerEndpoint list that will be used in the DataCacheFactoryConfiguration (see line 13).

  • Line 7: Add the endpoint (defined by the service URL and port) to the list.

  • Line 12: Set a DataCacheSecurity object using the authorization token for the SecurityProperties property.

  • Line 13: Set the DataCacheServerEndpoint list to the Servers property.

  • Line 18: Create a new DataCacheFactory and pass the DataCacheFactoryConfiguration object to the constructor.

Before getting started, but sure to prepare Visual Studio and provision or access your Cache to get the service URL and the authorization token.