title: XmlSerializer Caching Factory
body: <p>I <a href="http://dotnetcodebox.blogspot.com.au/2013/01/xmlserializer-class-may-result-in.html#comment-form" rel="nofollow">came across a factory class</a> and I'm not entirely sure how to use it if I am wanting to replace the following <code>XmlSerializer</code> code.</p>
  
  <p><strong>Sample Model</strong></p>
  
  <pre><code>public class SampleData
  {
      public string Name { get; set; }
      public string Country { get; set; }
  }
  </code></pre>
  
  <p><strong>Existing Code</strong></p>
  
  <pre><code>List&lt;SampleData&gt; objects = new List&lt;SampleData&gt;();
  objects.Add(new SampleData() { Country = "Australia", Name = "aus" });
  
  StringWriter writer = new StringWriter();
  
  XmlSerializer serializer = new XmlSerializer(typeof(List&lt;SampleData&gt;));
  serializer.Serialize(writer, objects);
  </code></pre>
  
  <p><strong>Factory Class</strong></p>
  
  <pre><code>public static class CachingXmlSerializerFactory
  {
      private static readonly Dictionary&lt;string, XmlSerializer&gt; Cache = new Dictionary&lt;string, XmlSerializer&gt;();
  
      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&lt;T&gt;(XmlRootAttribute root)
      {
          return Create(typeof(T), root);
      }
  
      public static XmlSerializer Create&lt;T&gt;()
      {
          return Create(typeof(T));
      }
  
      public static XmlSerializer Create&lt;T&gt;(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);
      }
  }
  </code></pre>