Written by 8:27 am Libraries, Protocol BUffers

Creating .proto definitions from existing types at runtime

Jared Rhodes, Microsoft MVP and Pluralsight Author, showcases how to create Protocol Buffer definitions from existing classes. This post focuses on EFCore but can be generalized to any different type definitions you would like to use.

There was a need to create .proto definition files from the definitions of a reverse engineered database first project. The approach taken was that of using System.Emit to generate the type definitions and feed those to protobuf-net and use its ability to generate the .proto files.

There are only three classes needed:

  • ContextFinder
  • ClassGenerator
  • Program

The ContextFinder is pretty straight forward. It uses reflection to get all the generic parameters of DbSet<> properties within a DbContext. Then, ClassGenerator is used to copy the properties of the Types we harvested into a new type with the addition of adding ProtoContract and ProtoMember appropriately. Then, the Program class just loads the assembly from the file specified and runs the previously two mentioned classes.

https://gist.github.com/QiMata/368efca0829362327c8e6ea8b6678e9b

Visited 1 times, 1 visit(s) today

Last modified: November 12, 2019

Close