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
// define the cache details
string serviceUrl = “YOURNAMESPACE.cache.appfabriclabs.com”;
string authorizationToken = “YOURTOKEN”;
// declare an array for the cache host
List
server.Add(new DataCacheServerEndpoint(serviceUrl, 22233));
// setup the DataCacheFactory configuration
DataCacheFactoryConfiguration conf = new DataCacheFactoryConfiguration();
conf.IsRouting = false;
conf.SecurityProperties = new DataCacheSecurity(authorizationToken);
conf.Servers = server;
conf.RequestTimeout = new TimeSpan(0, 0, 45);
conf.ChannelOpenTimeout = new TimeSpan(0, 0, 45);
// create the DataCacheFactor based on config settings
DataCacheFactory dataCacheFactory = new DataCacheFactory(conf);
// get the default cache client
DataCache dataCache = dataCacheFactory.GetDefaultCache();
// put and retrieve a test object
dataCache.Put(“key”, “1”);
string value = dataCache.Get(“key”) as string;
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.