RSCG – ProtobufSourceGenerator
| name | ProtobufSourceGenerator |
| nuget | https://www.nuget.org/packages/LaDeak.ProtobufSourceGenerator/ |
| link | https://github.com/ladeak/ProtobufSourceGenerator |
| author | Laszlo Deak |
Serializing a class to protobuf
This is how you can use ProtobufSourceGenerator .
The code that you start with is
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="LaDeak.ProtobufSourceGenerator" Version="1.5.1" OutputItemType="Analyzer" ReferenceOutputAssembly="true" />
<PackageReference Include="protobuf-net" Version="3.2.26" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>
The code that you will use is
using ProtoBuf;
using ProtobufSourceGeneratorDemo;
using var ms = new MemoryStream();
Serializer.Serialize(ms,new Person() { Name= "Andrei Ignat" });
ms.Seek(0,SeekOrigin.Begin);
var entity = Serializer.Deserialize<Person>(ms);
Console.WriteLine("name is "+entity.Name);
using ProtoBuf;
namespace ProtobufSourceGeneratorDemo;
[ProtoContract]
public partial class Person
{
public int Id { get; set; }
public string? Name { get; set; }
}
The code that is generated is
// <auto-generated/>
#nullable enable
namespace ProtobufSourceGeneratorDemo;
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
public partial class Person
{
[global::ProtoBuf.ProtoMember(1)]
private int ProtoId { get => Id; set => Id = value; }
[global::ProtoBuf.ProtoMember(2)]
private string? ProtoName { get => Name; set => Name = value; }
}
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/ProtobufSourceGenerator
Leave a Reply