protobuf-net.grpc Client Injection

Viewed 160

I was previously using Grpc.AspNetCore but am trying to migrate to protobuf-net.grpc because I much prefer the code-first approach given that it's more idiomatically dotnet and the whole solution is built on dotnet, so having .proto files and code-gens just causes a bit of a mess.

So I've created my service as per this guide:

[ServiceContract]
public interface IAdService
{
    [OperationContract]
    Task<HorseSaleAdReply> GetHorseSaleAds(AdRequest adRequest, CallContext context = default);
}

As far as I can tell, this works nicely.

However, I now want to create a client for this service and have it injected. The docs suggest this approach:

using var channel = GrpcChannel.ForAddress("https://localhost:7184");
        var client = channel.CreateGrpcService<IGreeterService>();

        var reply = await client.SayHelloAsync(
            new HelloRequest { Name = "GreeterClient" });

However, when I try and wrap that in a singleton:

builder.Services.AddSingleton(_ => {
using var channel = GrpcChannel.ForAddress("https://localhost:7184");
        return channel.CreateGrpcService<IAdService>();
})

And inject it into one of my classes, I get an error about the channel having already been disposed.

Would you be able to advise on how I can correctly inject these clients?

My only other idea would be to create a client class that implements IDisposable, stores a reference to that channel and does it that way. However, this seems like it really ought to be unnecessary.

0 Answers
Related