ToBu
ToBu

Reputation: 95

Use protobuf-net RuntimeTypeModel with GrpcClient (AddCodeFirstGrpcClient)

i try to use a custom protobuf-net RuntimeTypeModel with the protobuf-net grpc client library. What I understand so far, I need to to use the ClientFactory and set a binder-configuration which references my RuntimeTypeModel-Instance.

var binderConfig = BinderConfiguration.Create(new List<MarshallerFactory> {
    ProtoBufMarshallerFactory.Create(_runtimeTypeModel)
}); 
var clientFactory = ClientFactory.Create(binderConfig)

This is working, if i create the client and the underlying grpc-channel every time myself.

Now, I want to use the GrpcClientFactory via DI provided by the nuget package protobuf-net.Grpc.ClientFactory

I don't know, how to configure the ClientFactory to use my custom RuntimeTypeModel. In my startup I tried the following:

.AddCodeFirstGrpcClient<IMyGrpcService>(o =>
{
   o.Address = new Uri("https://localhost:5001");
   o.Creator = (callInvoker) =>
   {
       var servicesProvider = services.BuildServiceProvider(); 
       var binderConfig = BinderConfiguration.Create(new List<MarshallerFactory> {
            ProtoBufMarshallerFactory.Create(servicesProvider.GetService<RuntimeTypeModel>())
        });

       var clientFactory = ClientFactory.Create(binderConfig);
       return clientFactory.CreateClient<IMyGrpcService>(callInvoker);
   };
});

I can use IMyGrpcService in my controller classes and get a valid instance. But the o.Creator delegate is never called and the wrong runtimeTypeModel is used.

What is wrong with this approach?

Thanks. Toni

Upvotes: 1

Views: 1066

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

You need to register the ClientFactory with the DI layer:

services.AddSingleton<ClientFactory>(clientFactory)

Now it should discover it correctly. You should not need to set the Creator.

(note: it doesn't specifically need to be a singleton, but: that should work)

Upvotes: 1

Related Questions