Search code examples
c#xml-serialization

How to exclude a class from the XML serialization assembly


I have a C# project where I have to activate XML serialization assembly generation (GenerateSerializationAssemblies in csproj).

The project contains a class that is derived from System.ComponentModel.Composition.ExportAttribute.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class MyExportAttribute : ExportAttribute
{ ... }

The compiler fails with an error complaining about a missing public property setter on ExportAttribute.ContractName:

Error 10 Cannot deserialize type 'System.ComponentModel.Composition.ExportAttribute' because it contains property 'ContractName' which has no public setter. 

Actually I do not want to serialize this class, so I'd like to exclude it from the serialization assembly. Can I do that? Or alternatively, specify which classes to include?

What I've tried / thought of so far:

  • Hide the ContractName property (non virtual) in MyExportAttribute with an empty setter, call the base implementation in the getter -> same error, serializer still wants to access the properties on the base class
  • Applying XmlIgnore to that MyExportAttribute.ContractName did not help either
  • Moving classes to other projects is an option, but I'd like to avoid that if possible
  • XmlIgnore on the ContractName property would solve my problem, but of course I cannot add it to ExportAttribute. Is there a similar XML serialization control attribute that can be applied to a class, so that it's ignored by the serializer?

Solution

  • To work around this error, I implemented IXmlSerializable on the class that gave sgen issues. I implemented each required member by throwing NotImplementedException:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public class MyExportAttribute
        : ExportAttribute
        // Necessary to prevent sgen.exe from exploding since we are
        // a public type with a parameterless constructor.
        , System.Xml.Serialization.IXmlSerializable
    {
        System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() => throw new NotImplementedException("Not serializable");
        void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) => throw new NotImplementedException("Not serializable");
        void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) => throw new NotImplementedException("Not serializable");
    }