Serialize to XML - private properties

二次信任 提交于 2019-11-30 18:03:53

问题


I'm looking for a way to serialize a POCO that contains some read-only properties. In some Google and StackOverflow searches, I've seen the following suggestions:

  • use DataContractSerializer; or
  • use SoapFormatter or BinaryFormatter; or
  • replace my readonly properties by read/write properties;

My classes are very simple, they look like:

public class MyClass
{
    public int Id { get; private set; }
    public string Name { get; private set; }
    public MyClass(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

So,

  • I don't want to make my properties read/write. If they are read-only, it's because my domain model asks for read-only properties. The domain model cannot change just because of this.
  • I don't want to use DataContractSerializer, as this would pollute my domain model with serialization-related stuff.
  • BinaryFormatter is not a very good option, as the result is a byte[], and I would like to treat it as string (and I don't want to deal with Encondings and alike when Deserializing my object).

What I would really like is an XmlSerializer class capable of serializing read-only properties.

Do you know of any such implementation? Or any other convenient solution?

Thanks!


回答1:


Well, normally XmlSerializer can't serialize read-only properties... however there is a possibility to serialize properties with an internal set : you need to generate the XML serialization assembly, and declare it as a "friend" assembly using the InternalsVisibleTo attribute. You can automate this by adding the following code to your project file :

  <Target Name="AfterBuild"
          DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource"
          Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)"
          Outputs="$(OutputPath)$(_SGenDllName)">
    <SGen BuildAssemblyName="$(TargetFileName)"
          BuildAssemblyPath="$(OutputPath)"
          References="@(ReferencePath)"
          ShouldGenerateSerializer="true"
          UseProxyTypes="false"
          KeyContainer="$(KeyContainerName)"
          KeyFile="$(KeyOriginatorFile)"
          DelaySign="$(DelaySign)"
          ToolPath="$(SGenToolPath)">
      <Output TaskParameter="SerializationAssembly"
              ItemName="SerializationAssembly" />
    </SGen>
  </Target>

And in AssemblyInfo.cs :

[assembly: InternalsVisibleTo("MyAssembly.XmlSerializers")]

Of course, you might not want the properties to have an internal set, but if you do, the solution above should work.




回答2:


While it would be sweet if serialize could access private properties unfortunately as of today there is no easy way.

But there is another option in the way of an architecture solution. Do NOT destroy your business domain requirements, instead seperate your layers similar to a a nTeir design and implement DTO's...

If you seperate your business, datafacade/dataadaptor (factory pattern fits well here) and DataAccess layers into 3 projects you can control through referencing that business never know about your DTO's. Hense if you decided to delete or implement the serialization or swap it to saving to SQL server you would not affect anything in your business layer.

There is always one downfall, there is a bunch more code to write: * you have to write a object convertor both ways for each entity you wish to go to Dataaccess * you potentially destroy some of the OO hiding sinse a .Save method in business will need to be translated to the correct type in Dataface before moving on down to dataaccess

You can make this a whole lot more easy with something like nHybinate or similar. Cheers Choco



来源:https://stackoverflow.com/questions/1347102/serialize-to-xml-private-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!