views:

399

answers:

3

I've got a class which uses an XmlSerializer in its Read/WriteXml methods. The Serializer is currently private readonly.

public class Foo : IXmlSerializable
{
    private Bar _bar = new Bar();
    private readonly XmlSerializer serBar = new XmlSerializer (typeof (Bar));

    public void WriteXml (XmlWriter writer)
    {
        serBar.Serialize (writer, Bar);
    }
    // ...
}

I'm considering making the Serializer private static instead, so one instance is shared between all Foos. Is this a good idea, or are there possible issues?

+5  A: 

Yes, it is a good idea. No, there aren't any issues with it. In particular, thread safety is not an issue - from MSDN documentation for XmlSerializer class:

Thread Safety

This type is thread safe.

Pavel Minaev
Ah, great, this is going to be the accepted answer unless something new comes up. :)
mafutrct
+1  A: 

Yes. In general you'll want to do this for all of your serializer classes. It can dramatically speed up your application

The easiest way to do this is:

public static class MySerializers {
   public static XmlSerializer MyType = new XmlSerializer(typeof(MyType));    
}

Then when you need a serializer you can simply call:

MySerializers.MyType

Also note that according to C# semantics, static classes are initialized on first use, not at load-time. If you want to put all the load cost up front, you'll need to explicitly access the class.

Neal Tibrewala
Good idea, thanks! +1
mafutrct
+3  A: 

One way would be to create an XmlSerializers factory and reference it statically (or as an IoC reference), something like:

public class XmlSerializerFactory
{
    public XmlSerializer GetSerializerFor<T>()
    {
        lock (this)
        {
            Type typeOfT = typeof(T);
            if (false == serializers.ContainsKey(typeOfT))
            {
                XmlSerializer newSerializer = new XmlSerializer(typeOfT);
                serializers.Add(typeOfT, newSerializer);
            }

            return serializers[typeOfT];
        }
    }

    private Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();
}
Igor Brejc