Search code examples
c#.netgrpcdotnet-httpclient

is it possible to instance as singleton a http client with HttpClientFactory for a gRPC client?


it seems it is not a good practice to create a HttpClient for each call to the server. This is commented here: https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Reading the documentation about HttpClientFactory, https://www.nuget.org/packages/Grpc.Net.ClientFactory, it is said that the client is registered as transient, so it can be injected as dependency property.

Well, if the client is created as transient, it is creadted for each view model that need to use the service, so the advise that says that the life of the http client should to be for the whole life of the applications it is not followed. So I guess that I should to register the client as singlenton.

Is it possible to use the factory to register the client as singlton instead of transient?

Thanks.


Solution

  • I do not think this article applies to gRPC that much. The client performace section in the MS gRPC documentation says: gRPC clients are lightweight objects and don't need to be cached or reused. The performance heavy task seems to be the re-creation of gRPC channels, which use the HttpClientMessageHandler type.