|
| 1 | +# Register Client Service |
| 2 | + |
| 3 | +## What is it? |
| 4 | + |
| 5 | +> Client service lets you to inject Grpc client dependency to your controllers. |
| 6 | +
|
| 7 | +## Register client service |
| 8 | + |
| 9 | +``` c# |
| 10 | +public void ConfigureServices(IServiceCollection services) |
| 11 | +{ |
| 12 | + // other service setup above ... |
| 13 | +
|
| 14 | + //this registers ICalculator Grpc client service |
| 15 | + services.AddCodeFirstGrpcClient<ICalculator>(o => { |
| 16 | + |
| 17 | + // Address of grpc server |
| 18 | + o.Address = new Uri(Configuration.GetValue<string>("https://localhost:5001")); |
| 19 | + |
| 20 | + // another channel options (based on best practices docs on https://docs.microsoft.com/en-us/aspnet/core/grpc/performance?view=aspnetcore-6.0) |
| 21 | + o.ChannelOptionsActions.Add(options => |
| 22 | + { |
| 23 | + options.HttpHandler = new SocketsHttpHandler() |
| 24 | + { |
| 25 | + // keeps connection alive |
| 26 | + PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan, |
| 27 | + KeepAlivePingDelay = TimeSpan.FromSeconds(60), |
| 28 | + KeepAlivePingTimeout = TimeSpan.FromSeconds(30), |
| 29 | + |
| 30 | + // allows channel to add additional HTTP/2 connections |
| 31 | + EnableMultipleHttp2Connections = true |
| 32 | + }; |
| 33 | + }); |
| 34 | + }); |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | +## How use it? |
| 39 | + |
| 40 | +Then in your controller you can use the registered dependency. |
| 41 | + |
| 42 | +``` c# |
| 43 | +public class GrpcController : Controller |
| 44 | +{ |
| 45 | + private readonly ICalculator _calculatorClient; |
| 46 | + public GrpcController(ICalculator calculatorClient) |
| 47 | + { |
| 48 | + _calculatorClient = calculatorClient; |
| 49 | + } |
| 50 | + |
| 51 | + //otestovat |
| 52 | + public async Task<int> Multiply(int x, int y) |
| 53 | + { |
| 54 | + |
| 55 | + var result = await _calculatorClient.MultiplyAsync(new MultiplyRequest { X = x, Y = y }); |
| 56 | + |
| 57 | + return result; |
| 58 | + } |
| 59 | +} |
| 60 | +``` |
0 commit comments