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:
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.
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