James
James

Reputation: 9985

Is it possible to merge RuntimeTypeModel's in protobuf-net

From what I've read/seen there are 3 ways to define the model for protobuf, with .proto files, with class decoration and with runtime calls to add types and fields. What I'm looking for is a way a bit more like FluentNhibernate where definition of the model is removed to seperate files away from the program for each class individually to leave the model cleaner. In this line of thought I've create a class Buffer<T> which when instantiated adds the class it is defining to a type model.

public class CustomerBuffer : Buffer<Customer>
{
    public CustomerBuffer()
    {
        Add("ID");
        Add("SyncID");
        Add("AccountNumber");
        Add("Reference");
        Add("Contact");
        Add("Address");
        Add("CreditInformation");
    }
}

the type model used is created in the Buffer<T> constructor so it is available when the derived classes constructor is called.

When everything has been added I need to be able to merge the models together so they can be compiled.

So far I've tried this:

foreach(MetaType MT in model.GetTypes())
{
    InternalModel.Add(MT.Type, false);
}

which obviously won't work since it's not copying the field information on the original MetaType.

So I'm looking for a work around which will allow me to search for and add all types deriving from Buffer<T> within an assembly (or multiple assemblies) to a type model and then compile it.

Upvotes: 2

Views: 738

Answers (2)

Simon Labrecque
Simon Labrecque

Reputation: 597

Take a look at Fluent protobuf-net: it does exactly what you want, I think (eg, Fluent NHibernate-like).

Upvotes: 1

James
James

Reputation: 9985

Solved this by using a Singleton for the type model. This way I don't need to merge type models since everything is added to the same model. Did need to add an override to AddSubType so that it could be called without the type number. This works nicely now.

Update

This causes me 2 errors so far both based on initialisation order of the classes being added.

"Unable to cast type x to type y" Occurs in ProtoWriter and ProtoReader when the base class is initialised after the subclass. - This has been solved by added a sort algorithm to wrapping protobufcfg class between finding all the types to initialise and actually initialising them.

"Possible Recursion Detected" Occurs when a Parent containing a property which is a list of children is initialised after the child and the child contains a "Parent" property.

Update2

Both these bugs are through my misuse of the AsReference Property, which needed to be dynamic as well as reference on the "Parent" property of the child and needed to be removed from the list.

Upvotes: 1

Related Questions