简体   繁体   English

使用 ASP.NET 核心 DI 容器注册“类型化”gRPC 客户端

[英]Registering a “typed” gRPC client with the ASP.NET Core DI container

I have a GrpcService class the takes in gRPC client in its constructor, like so:我有一个 GrpcService class 在其构造函数中接收 gRPC 客户端,如下所示:

public class GrpcService : IService 
{
    private readonly GrpcClient grpcClient;
 
    public GrpcService(GrpcClient grpcClient)
    {
        this.grpcClient = grpcClient;
    }
    
    //...
}

I have registered the gRPC client in the Startup class by using the generic AddGrpcClient extension method:我已经使用通用的 AddGrpcClient 扩展方法在 Startup class 中注册了 gRPC 客户端:

services.AddGrpcClient<GrpcClient>(o =>
{
    o.Address = new Uri("https://localhost:5001");
});

Now I want to inject the GrpcService class into a API controller.现在我想将 GrpcService class 注入到 API controller 中。 My question is;我的问题是; what's is the correct way to register the GrpcService in the Startup class?在启动 class 中注册 GrpcService 的正确方法是什么?

I did try the following, which did not work:我确实尝试了以下方法,但没有奏效:

services.AddGrpcClient<GrpcService>(); 

At the moment I have the following code, which works fine:目前我有以下代码,它工作正常:

services.AddSingleton<IService, GrpcService>();

However, I'm not certain using a singleton is the correct lifetime to use, in particular as the gRPC client uses HttpClient internally?但是,我不确定使用 singleton 是正确的生命周期,特别是当 gRPC 客户端在内部使用 HttpClient 时?

According to MS docs, that would be a singleton. 根据 MS 文档,那将是 singleton。

What you're looking for is here 你要找的就在这里

If you change services.AddGrpcClient<GrpcService>();如果您更改services.AddGrpcClient<GrpcService>(); to services.AddGrpcClient<GrpcClient>();services.AddGrpcClient<GrpcClient>(); and inject GrpcClient in your consumer constructor it should work.并在您的消费者构造函数中注入GrpcClient它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM