Reputation: 175
I am creating a .NET 8 Blazor application that has two projects – (server and client). I am having a problem with dependency injection (DI) not working on the client side of things. To keep things simple, I have a simple service class as defined below:
public class TestDi
{
public TestDi() { }
}
In my client’s Program.cs file I have defined DI as:
Other code…….
builder.Services.AddScoped<TestDi>();
await builder.Build().RunAsync();
In my component I have the following code:
@page "/test"
@rendermode InteractiveWebAssembly
Using statements….
@inject TestDi _testDi
When I run the app I get the following
InvalidOperationException: Cannot provide a value for property '_testDi' on type 'Invoice.Client.Pages.TestAuth'. There is no registered service of type 'Invoice.Client.ApiClient.TestDi'.
It is like the component doesn’t see the registered service. I used InteractiveWebAssembly to make sure the component is running using Web Assembly and not on the server.
Now if I define “builder.Services.AddScoped();” on the server side program.cs AND the client side program.cs it works. If I just define it on the server side it doesn’t – which is expected as it is running as wasm.
It is not practical for me to define DI in both the server side program.cs and client side program.cs with my real life service class as my real life service class has other DI dependencies such as ILocalStorageService, and HttpClient. Also, for other applications that I am upgrading to .NET 8, I really do not want to start creating two implementations: one for server rendering and another for client. I do not care about the few seconds of load time with wasm.
Any help would be appreciated.
Thanks, Bob
Upvotes: 5
Views: 3028
Reputation: 21
Setting the rendering mode to this should help:
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
Upvotes: 2
Reputation: 30167
Your components are pre-rendering to con the user into thinking things have loaded fast.
You can either:
Upvotes: 5