如何使用 Grpc 和 protobuf-net 在 Blazor Web Assembly 中注入依赖项

How to inject dependencies in Blazor Web Assembly using Grpc and protobuf-net

我正在构建一个 Web Assembly Blazor 和 Grpc,使用 protobuf-net 来处理服务。我正在尝试以这种方式注入我想要的服务:

builder.Services.AddSingleton(typeof(ICustomerService), services =>
        {
            // Create a gRPC-Web channel pointing to the backend server
            var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
            var channel = Grpc.Net.Client.GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions { HttpClient = httpClient });

            // Now we can instantiate gRPC clients for this channel
            return channel.CreateGrpcService<ICustomerService>();
        });

然后,我将我认为应该依赖的东西注入到razor组件中:

[Inject] ICustomerService Client { get; set; }

但是我得到这个错误:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Cannot provide a value for property 'Client' on type 'Customer_Create'. There is no registered service of type 'ICustomerService'.

非常感谢任何帮助!

我没有在 blazor 中专门尝试过这个,但总的来说:你正在寻找 Client Factory support, which works exactly like documented here 除了你使用 AddCodeFirstGrpcClient 方法注册:

services.AddCodeFirstGrpcClient<IMyService>(o =>
{
    o.Address = new Uri("...etc...");
});