Regular visitors of my blog will know that I’ve written a lot of posts about the HttpClientFactory feature, available in the Microsoft.Extensions.Http package which simplifies the consumption and proper lifetime usage of HttpClient instances.
Recently, I’ve begun digging into gRPC and I’m pleased to see a similar pattern is available for gRPC-based communication.
In this post, I want to show a quick example of how to get started with the gRPC Client Factory. I’m going to focus on adding this to an ASP.NET Core 3.0 web project, which will act as a client of an external gRPC service. This post assumes a little knowledge about gRPC. You can read my earlier blog post (slightly outdated now) which covers some extra ground.
The first step is to install the Grpc.Net.ClientFactory NuGet package into your project, along with the other libraries required to establish a gRPC client.
Note that these features are still in preview so I’m using the currently available pre-release versions from NuGet.
I also need to reference a proto file which contains the service contract for the service I will be consuming.
I’ll add a Protobuf file and tell the tooling to generate the client stubs for it.
Registering a gRPC Client
Registering a gRPC client is very similar to registering a HttpClient.
In ConfigureServices, on the IServiceCollection, we can call AddGrpcClient which access a generic argument to the client stub generated by the gRPC tooling.
Here I pass in the code-generated WeatherForecastsClient which exists thanks to the build tooling that generated it for me from the proto file.
I can pass the base address which is the HTTPS URL to the gRPC server which is hosting the service.
Finally, I can now inject instances of the client wherever I need them via constructor injection. As with HttpClientFactory, the clients are registered as transient services, with the underlying connection (channels) being managed for us.
That’s it for the basic use of the gRPC client factory. It’s all pretty simple to get started with. There are some other things we can do when registering the client which I’ll focus on in some future blog posts.