Serialization 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 supports three different modes of serialization. Each item that is stored in the cache must first be serialized into a persistent stream. Each item that is retrieved from the cache must be deserialized back into its object format. This topic describes the serialization options available in caching.
Serialization Types
The following table describes the three serialization types.
Configuration Setting | Description |
---|---|
NetDataContractSerializer |
Serializes objects with the NetDataContractSerializer class. This is the default. |
BinaryFormatter |
Serializes objects with the BinaryFormatter class. |
CustomSerializer |
Serializes objects using a custom serialization class provided by the application. |
If no serialization option is specified, caching uses the NetDataContractSerializer. Note that any classes that are stored in the cache must be marked as Serializable.
In the configuration file, you can specify the serializationProperties element as a child of the dataCacheClient element. The following example demonstrates a dataCacheClients section with two named cache clients. The default cache client uses the default serialization, and the second cache client specifies binary serialization.
<dataCacheClients>
<dataCacheClient name="default">
<autoDiscover isEnabled="true" identifier="WebRole1" />
</dataCacheClient>
<dataCacheClient name="binaryConfig">
<serializationProperties serializer="BinaryFormatter" />
<autoDiscover isEnabled="true" identifier="WebRole1" />
</dataCacheClient>
</dataCacheClients>
The following example shows how you would access each of these cache client configurations in code.
// "default" cache client configuration, "default" cache:
DataCache cacheTest1 = new DataCache();
cacheTest1.Put("test", "test");
// "binaryConfig" cache client configuration, "default" cache:
DataCache cacheTest2 = new DataCache("default", "binaryConfig");
cacheTest2.Put("test", "test");
Custom serialization requires additional coding. For more information, see How to: Use a Custom Serializer with Azure In-Role Cache.
Note
The programmatic equivalent of the serializationProperties element is the DataCacheSerializationProperties class. The properties on this class correspond to the same three serialization types. This enumeration is assigned to the DataCacheFactoryConfiguration.SerializationProperties property.
Important
The ASP.NET providers for caching do not support binary or custom serialization types.