Serialize Value Objects | Vogen (original) (raw)
Vogen integrates with various serializers, including:
- JSON (
System.Text.Json
andNewtonsoft.Json
) - BSON
- Dapper
- LinqToDB
- EF Core
- ASP.NET Core (for MVC routes etc.), by generating a
TypeConverter
- protobuf-net (see the section in the FAQ for usage)
… and many others. See the Conversions
attribute for a full list.
This conversion code can be generated in the same project as the value object or in a different project. Using a different project is allows you to follow architecture patterns where you separate infrastructure from other layers.
Conversion code in the same project
Here are two types where we want serializers for MessagePack and Mongo's BSON format:
[ValueObject( conversions: Conversions.MessagePack | Conversions.Bson)] public readonly partial struct Name { } [ValueObject( conversions: Conversions.MessagePack | Conversions.Bson)] public readonly partial struct Age { }
If you're following an architecture pattern where you separate infrastructure from other layers, then you'll want the generated converters to live in another project. This is described below.
Conversion code in a different project
Create a partial class
(not a struct
), and specify what converters you want for what type. For the two examples above, it'd be:
[BsonSerializer<Domain.Name>] [BsonSerializer<Domain.Age>] public partial class BsonConversions; [MessagePack<Domain.Name>] [MessagePack<Domain.Age>] public partial class MessagePackConversions;
... or just have them in one class:
[BsonSerializer<Domain.Name>] [MessagePack<Domain.Name>] [BsonSerializer<Domain.Age>] [MessagePack<Domain.Age>] public partial class Conversions;
And reference them with something like Conversions.NameBsonSerializer
etc. Here's an example to register all MessagePack formatters:
var customResolver = MessagePack.Resolvers.CompositeResolver.Create( Conversions.MessagePackFormatters, [MessagePack.Resolvers.StandardResolver.Instance] );
Integrations
For generating conversions in the same project, use the conversions
parameter in the ValueObject
attribute:
using System; namespace Vogen; ///
The default, as specified above in the Defaults
property, is TypeConverter
and SystemTextJson
.
If you don't want any conversions, then specify Conversions.None
.
If you want your own conversion, then again specify none and implement them yourself, just like any other type. Be aware that even serializers will get the same compilation errors for new
and default
when trying to create VOs.
There may be other steps that you need to do to use these integrations, for instance, for Dapper, register it—something like this:
SqlMapper.AddTypeHandler(new Customer.DapperTypeHandler());
See the examples folder for more information.
Last modified: 06 June 2025