Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call PrepareSerializer without Generic classes

Tags:

protobuf-net

I use reflection find all the Classes in my project that Inherit from Packet.Base

Each of these classes has ProtoBuf attributes applied.

I've just experienced Protobuf.net Exception - Timeout while inspecting metadata my project and want to implement the PrepareSerializer without having to go through and add all the different class types in there.

Is there a simple way that I can dynamically prepare the classes given that I have the type from reflection without needing to call

ProtoBuf.Serializer.PrepareSerializer(Of Instruction)()
ProtoBuf.Serializer.PrepareSerializer(Of NoOperation)()

or adding a

Public MustOverride Sub Prepare()

to the base class and then in each class

Public Overrides Sub Prepare()
    Serializer.PrepareSerializer(Of TimeSynchronise)()
End Sub

This is the loading mechanism i'm using, a pretty simple reflection load.

Public Class CompatiblePackets
    Inherits Dictionary(Of Packet.PacketType, Base)

    Public Sub New()
        Dim theAssembly As Assembly = Assembly.GetExecutingAssembly
        For Each t As Type In theAssembly.GetTypes
            If t.BaseType Is GetType(Base) Then
                Dim p As Base = CType(t.Assembly.CreateInstance(t.FullName), Base)
                Me.Add(p.PacketTypeIndicator, p)
                End Try
            End If
        Next
    End Sub

    public sub Prepare
        ProtoBuf.Serializer.PrepareSerializer(t)()
    end sub 
like image 266
Paul Farry Avatar asked Apr 23 '26 16:04

Paul Farry


1 Answers

Yes, you can call that without generics:

RuntimeTypeModel.Default[type].CompileInPlace();

where:

  • RuntimeTypeModel.Default is the default type-model, which is what the Serializer.* methods use (v2 supports parallel independent type-models)
  • the [type] indexer performs and implicit Add if it is missing, using the default behaviours (attributes) - and thus does most of the metadata analysis
  • the CompileInPlace() does IL optimisation for the type

You can also try increasing RuntimeTypeModel.Default.MetadataTimeoutMilliseconds slightly.

like image 125
Marc Gravell Avatar answered May 04 '26 08:05

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!