Grpc service in .Net Core is recreated for every client request

Viewed 1076

Currently I'm doing some experimenting with .Net Core 3.1 and Grpc/Protobuf. I've defined a proto interface for a Robot, that generates the Grpc code for both client and server. From what I read in the documentation is that the connection between client and server is maintained by a GrpcChannel.

_grpcChannel = GrpcChannel.ForAddress("https://localhost:5001");
_grpcRobotClient = new Robot.RobotClient(_grpcChannel);

The code above is only touched once, so there's really only one _grpcRobotClient, using a single _grpcChannel. I would now expect every call from this client to reach the same (instance of) server endpoint, which is created in the Startup.cs of my Grpc server, very similar to the "GreetingService" example which is all over the internet (and unfortunately seems to be the only good example out there):

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
     if (env.IsDevelopment())
     {
        app.UseDeveloperExceptionPage();
     }

     app.UseRouting();

     app.UseEndpoints(endpoints =>
     {
        endpoints.MapGrpcService<RobotService>();
     });
  }

The RobotService class has a constructor that sets up a connection to - you guessed it - a robot. Of course I would like this robot connection to be persistent. What I'm seeing though is that for every request on the GrpcChannel a new instance of GrpcService is created and so my current robot connection gets disposed.

I've been able to work around this by making the robot connection a static property of the RobotService, but that should not be needed, right? I mean, that's just nasty. No need to lecture me about that.

So, I'm either missing something important in the setup of my server endpoint or I have to configure some extra ChannelOptions - maybe? Anyone has a clue what's going wrong here?

1 Answers

you need to enable grpc web at the endpoint:

enter code here
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
 if (env.IsDevelopment())
 {
    app.UseDeveloperExceptionPage();
 }

 app.UseRouting();
 //missing point
 //app.UseGrpcWeb() and then you can enable on each service by using .EnableGrpcWeb(); 
 //Or enable grpc web for all as below and you might need to use cors too.
 app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });
 app.UseEndpoints(endpoints =>
 {
    endpoints.MapGrpcService<RobotService>();
 });
 }
Related