I came across a factory class and I'm not entirely sure how to use it if I am wanting to replace the following XmlSerializer
code.
Sample Model
public class SampleData
{
public string Name { get; set; }
public string Country { get; set; }
}
Existing Code
List<SampleData> objects = new List<SampleData>();
objects.Add(new SampleData() { Country = "Australia", Name = "aus" });
StringWriter writer = new StringWriter();
XmlSerializer serializer = new XmlSerializer(typeof(List<SampleData>));
serializer.Serialize(writer, objects);
Factory Class
public static class CachingXmlSerializerFactory
{
private static readonly Dictionary<string, XmlSerializer> Cache = new Dictionary<string, XmlSerializer>();
private static readonly object SyncRoot = new object();
public static XmlSerializer Create(Type type, XmlRootAttribute root)
{
if (type == null) throw new ArgumentNullException("type");
if (root == null) throw new ArgumentNullException("root");
var key = String.Format(CultureInfo.InvariantCulture, "{0}:{1}", type, root.ElementName);
lock (SyncRoot)
{
if (!Cache.ContainsKey(key))
{
Cache.Add(key, new XmlSerializer(type, root));
}
}
return Cache[key];
}
public static XmlSerializer Create<T>(XmlRootAttribute root)
{
return Create(typeof(T), root);
}
public static XmlSerializer Create<T>()
{
return Create(typeof(T));
}
public static XmlSerializer Create<T>(string defaultNamespace)
{
return Create(typeof(T), defaultNamespace);
}
public static XmlSerializer Create(Type type)
{
return new XmlSerializer(type);
}
public static XmlSerializer Create(Type type, string defaultNamespace)
{
return new XmlSerializer(type, defaultNamespace);
}
}
Reread the section that article quotes from MSDN. You're already using one of the two constructors that caches the internal serializer, and thus it should not result in a memory leak. If you were using one of the other constructors, you would need to worry about caching the XmlSerializer
, but you are not. No need to fix what isn't broken. ;-)