How to: Create a DataCache Object in RoleEntryPoint Methods in Azure In-Role Cache

Important

Microsoft recommends all new developments use Azure Redis Cache. For current documentation and guidance on choosing an Azure Cache offering, see Which Azure Cache offering is right for me?

Microsoft Azure Cache settings in the web.config file are not automatically available from in the context of the RoleEntryPoint class (typically defined in the WebRole.cs file). When you attempt to create a DataCache object in the RoleEntryPoint class methods, the following error occurs:

{"ErrorCode<ERRCA0021>:SubStatus<ES0001>:Server collection cannot be empty."}

This happens because the dataCacheClient settings in the web.config file are not automatically being applied to the new DataCache client object. Specifically, the attributes of the autoDiscover element are unavailable, so the DataCache object is unable to target the role that hosts caching.

In this scenario, you must programmatically configure a DataCacheFactoryConfiguration object, which accesses the settings in the web.config file directly.

How to Programmatically Configure a Cache Client

  1. Create a DataCacheFactoryConfiguration object.

    DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration();
    
  2. Set the AutoDiscoveryProperty to a new DataCacheAutoDiscoverProperty object. Specify true to enable automatic discovery. Also specify the name of the role that hosts caching.

    config.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, "WebRole1");
    
  3. Set any other properties on the DataCacheFactoryConfiguration object that control the behavior of the cache client.

  4. Create a DataCacheFactory object, passing the DataCacheFactoryConfiguration object in the constructor.

    DataCacheFactory factory = new DataCacheFactory(config);
    
  5. Call the DataCacheFactory.GetCache method to return the DataCache object for the target named cache.

    DataCache cache = factory.GetCache("default");
    

Example

// Create a DataCacheFactoryConfiguration object
DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration();

// Enable the AutoDiscorveryProperty (and any other required configuration settings):
config.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, "WebRole1");

// Create a DataCacheFactory object with the configuration settings:
DataCacheFactory factory = new DataCacheFactory(config);

// Use the factory to create a DataCache client for the "default" cache:
DataCache cache = factory.GetCache("default");

See Also

Concepts

Getting Started with Development for Azure In-Role Cache