Skip to content

Grpc: Clients

ronimizy edited this page Feb 10, 2024 · 6 revisions

General

Use AddPlatformGrpcClients extensions method on IServiceCollection to configure gRPC clients in your application. It accepts a delegate that allows you to configure builder for client configurations.

Samples

Services

Platform library binds clients to services. This allows you to specify configuration for specific service just once, and clients for multiple gRPC services located on it.

You can use AddService method on builder provided by AddPlatformGrpcClients. You must specify service name, and provide its configuration.

.AddService(service => service
    .Called("sample")
    .WithConfiguration(configuration.GetSection("Sample:Grpc"))

Configuration schema

{
  "Address": string
}
  • Address
    An url to service you want to configure

Configuration example

{
  "Sample": {
    "Grpc": {
      "Address": "localhost:8080"
    }
  }
}

Clients

After you configured service, you can add a client for it using WithClient method.

.AddService(service => service
    .Called("sample")
    .WithConfiguration(configuration.GetSection("Sample:Grpc"))
    .WithClient<SampleService.SampleServiceClient>())

Interceptors

This library provides a convenient way to register client interceptors (interceptors are automatically registered in DI). There are several ways you can configure interceptors.

Per client

To configure interceptors per client pass a delegate to WithClient method

.AddService(service => service
    ...
    .WithClient<SampleService.SampleServiceClient>(c => c.WithInterceptor<SampleClientInterceptor>())

Per service

To configure interceptors per service (for all clients bound to this service), call WithInterceptor at the end of call chain in delegate passed to AddService.

Note that per service interceptors must be configured after all clients added, you would not be able to call WithClient after WithInterceptor was called for service builder.

.AddService(service => service
    ...
    .WithInterceptor<SampleServiceInterceptor>())

Global

To configure interceptors globally (for all services), call WithInterceptor at the end of call chain in delegate passed to AddPlatformGrpcClients.

Note that global interceptors must be configured after all services added, you would not be able to call AddService after WithInterceptor was called for builder.

collection.AddPlatformGrpcClients(clients => clients
    ...
    .AddInterceptor<SampleGlobalInterceptor>());

Header providers

You can apply a header modifier for all gRPC requests via IPlatformGrpcHeaderProvider. Simply implement this interface and pass it to AddHeaderProvider method of builder provided by AddPlatformGrpcClients method.

collection.AddPlatformGrpcClients(clients => clients
    ...
    .AddHeaderProvider<HeaderProvider>()

Library will automatically register passed provider in DI, and will add provided headers to each request.