RenderMode Issues
When you have the problem where buttons don’t fire the functions you have assigned to them, here is the solution: If you purely want to enable it in a single component / selective: put @rendermode InteractiveServer
at the top of your component. This doesn’t work with MainLayout.razor
Changing <Routes />
in App.razor to <Routes @rendermode=@RenderMode.InteractiveServer />
This makes it so it is enabled everywhere, even in MainLayout.razor
.
You can theoretically remove all @rendermode InteractiveServer
from the components when you use this method, but you don’t need to.
Sharing Services With Components
Simple Method
In this example I wanted to share my custom event-handler: NewEventHandler
with all components. But it has to be the same event-handler instance. Here is how I did it:
In the program.cs
:
var eventHandler = new NewEventHandler();
builder.Services.AddSingleton<NewEventHandler>(eventHandler);
In your component: @inject NewEventHandler EventHandler
.
And now I can use this variable in the @code {}
code-blocks, or in the html.
And you can ofc also still use it in program.cs
.
Scope method
If you don’t need to share an specific instance, which you also need in your program.cs
. Here is how I did it:
in the program.cs
:
builder.Services.AddSingleton<DatabaseHandlerService>();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var databaseHandlerService = services.GetRequiredService<DatabaseHandlerService>();
// you can use it now in this scope
}
You can use it the same way as the simple method, In your component: @inject DatabaseHandlerService DatabaseHandlerService
And now I can use this variable in the @code {}
code-blocks, or in the html.
And you can ofc also still use it in program.cs
.
Only difference being, you can only use it in the scope and not the full program.cs
.