.net core Net核心中的Grpc服务将针对每个客户端请求重新创建

.net core Net核心中的Grpc服务将针对每个客户端请求重新创建,.net-core,grpc,endpoint,proto,.net Core,Grpc,Endpoint,Proto,目前我正在用.NETCore3.1和Grpc/Protobuf做一些实验。我已经为机器人定义了一个proto接口,它为客户端和服务器生成Grpc代码。从文档中我了解到,客户端和服务器之间的连接由GrpcChannel维护 _grpcChannel = GrpcChannel.ForAddress("https://localhost:5001"); _grpcRobotClient = new Robot.RobotClient(_grpcChannel); 上面的代码只接触过一次,所以实际上

目前我正在用.NETCore3.1和Grpc/Protobuf做一些实验。我已经为机器人定义了一个proto接口,它为客户端和服务器生成Grpc代码。从文档中我了解到,客户端和服务器之间的连接由GrpcChannel维护

_grpcChannel = GrpcChannel.ForAddress("https://localhost:5001");
_grpcRobotClient = new Robot.RobotClient(_grpcChannel);
上面的代码只接触过一次,所以实际上只有一个使用单个通道的grpcRobotClient。现在,我希望来自该客户端的每个调用都会到达相同的服务器端点(实例),该端点是在我的Grpc服务器的Startup.cs中创建的,与遍布互联网的“GreetingService”示例非常相似(不幸的是,它似乎是唯一一个好的示例):

public void配置(IApplicationBuilder应用程序,IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(端点=>
{
endpoints.MapGrpcService();
});
}
RobotService类有一个构造函数,用于建立到(您猜到了)机器人的连接。当然,我希望这个机器人连接是持久的。但我看到的是,对于GrpcChannel上的每个请求,都会创建一个新的GrpcService实例,因此我当前的robot连接会得到处理

我已经能够通过使机器人连接成为机器人服务的静态属性来解决这个问题,但这不应该是必需的,对吗?我的意思是,那太恶心了。没必要教训我


所以,我要么在服务器端点的设置中遗漏了一些重要的东西,要么我必须配置一些额外的通道选项——也许?有人知道这里出了什么问题吗?

您需要在端点启用grpc web:

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>();
 });
 }
在此处输入代码
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
//漏点
//然后您可以使用.EnableGrpcWeb()在每个服务上启用;
//或者如下所示启用grpc web,您可能也需要使用cors。
app.UseGrpcWeb(新的GrpcWebOptions{DefaultEnabled=true});
app.UseEndpoints(端点=>
{
endpoints.MapGrpcService();
});
}

在grpc dotnet中,默认情况下创建的服务具有“作用域”生存期。这在ASP.NET核心级别是可配置的(与配置DI提供的任何其他组件的方式相同)。更多文档请参阅。谢谢Jan,这正是我需要的信息。不知何故,在寻找答案的过程中,我错过了微软的这一页。
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>();
 });
 }