gRPC requests in .NET rely on channels, that must be shut down and disposed:
using var channel = Grpc.Net.Client.GrpcChannel.ForAddress("path to service");
//...do stuff...
await channel.ShutdownAsync();
I'm wrapping this in a .NET dependency injected service using IServiceCollection
, should this be...
- Per-method - create and dispose the channel inside each method call.
AddTransient
- a new channel every time my service is requested, but only as long as it's needed.AddScoped
- a new channel for each request, but keeping the channel open until the request is done.AddSingleton
- a single new channel for the app.
I think AddSingleton
is out as I'm not sure how one GrpcChannel
will handle lots of parallel requests at the same time and I'd like to pass the CancellationToken
for the current request.
Which puts the choice between AddScoped
vs AddTransient
vs per-method. Without a load of testing (and stumbling into all the pitfalls) I'm not sure what the best practice here is (I'm new to gRPC). Should I be closing the channel as soon as possible, or keeping it open and sharing it between calls?