0xSingularity
0xSingularity

Reputation: 570

Generate protobuf files from C# classes?

I have a C# GRPC library that I am converting, I have complex protobuf-net objects (defined in C#) using features like inheritance. How can I convert these objects to native .proto files? If possible, I would like it to use composition instead of inheritance.

i.e

[ProtoContract]
class Person {
    [ProtoMember(1)]
    public int Id {get;set;}
    [ProtoMember(2)]
    public string Name {get;set;}
    [ProtoMember(3)]
    public Address Address {get;set;}
}
[ProtoContract]
class Address {
    [ProtoMember(1)]
    public string Line1 {get;set;}
    [ProtoMember(2)]
    public string Line2 {get;set;}
}

output:

syntax = "proto3";

package example;

// Message definition for Address
message Address {
    string line1 = 1;
    string line2 = 2;
}

// Message definition for Person
message Person {
    int32 id = 1;
    string name = 2;
    Address address = 3;
}

Upvotes: 1

Views: 145

Answers (1)

Guru Stron
Guru Stron

Reputation: 141565

You can use Serializer.GetProto:

string proto = Serializer.GetProto<Person>();
Console.WriteLine(proto);

Which results in:

syntax = "proto3";

message Address {
   string Line1 = 1;
   string Line2 = 2;
}
message Person {
   int32 Id = 1;
   string Name = 2;
   Address Address = 3;
}

with the latest protobuf-net package.

Internally Serializer.GetProto calls RuntimeTypeModel.Default.GetSchema, which can be used to provide the package name:

var proto = RuntimeTypeModel.Default.GetSchema(new SchemaGenerationOptions
{
    Types = { typeof(Person) },
    Package = "example"
});

with output:

syntax = "proto3";
package example;

message Address {
   string Line1 = 1;
   string Line2 = 2;
}
message Person {
   int32 Id = 1;
   string Name = 2;
   Address Address = 3;
}

Upvotes: 3

Related Questions