Search code examples
protobuf-netblazor-client-sidegrpc-webblazor-webassembly

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


I am building a Web Assembly Blazor with Grpc using protobuf-net to handle the services. I am trying to inject the Service I want this way:

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>();
        });

Then, I inject what I think should be the dependecy into the razor component:

[Inject] ICustomerService Client { get; set; }

But I get this error:

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'.

Any help here is much appreciated!


Solution

  • I haven't tried this specifically in blazor, but in general: you're looking for the Client Factory support, which works exactly like documented here except you register with the AddCodeFirstGrpcClient method:

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