public class XmlSerializerCache
{
#region fields
private static Hashtable table;
#endregion // fields
#region constructors
static XmlSerializerCache()
{
XmlSerializerCache.table = new Hashtable();
}
private XmlSerializerCache()
{
}
#endregion // constructors
public static XmlSerializer GetXmlSerializer(Type type, string defaultNamespace)
{
XmlSerializer serializer;
if (type == null)
{
throw new ArgumentNullException("type");
}
// Make it thread safe
lock (XmlSerializerCache.table.SyncRoot)
{
string typeName;
if ((defaultNamespace == null) || (defaultNamespace.Length == 0))
{
typeName = type.FullName + "#";
}
else
{
typeName = type.FullName + "#" + defaultNamespace;
}
// Try to get the serializer from cache
object obj = XmlSerializerCache.table[typeName];
if (obj == null)
{
// We don't have it, create a new instance
obj = new XmlSerializer(type, defaultNamespace);
XmlSerializerCache.table.Add(typeName, obj);
}
serializer = obj as XmlSerializer;
}
return serializer;
}
}
The usage of the XmlSerializerCache should be pretty straightforward:
XmlSerializer serializer = XmlSerializerCache.GetXmlSerializer(typeof(Order), "http://tempuri.org/");
serializer.Serialize(stream, order);
BTW, you can employ this class for the desktop .NET as well too and enjoy some speed improvements.