I am following this example on passing tokens from HttpContext to components in a SSR application. It mentions the following:
An alternative to assigning the initial state to the TokenProvider in the preceding example is to copy the data into a scoped service within OnInitializedAsync for use across the app.
However, it seems that resolving the scoped service from App.razor causes it to initialized twice:
App.razor:
@inject Service Service<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><base href="/" /><link rel="stylesheet" href="bootstrap/bootstrap.min.css" /><link rel="stylesheet" href="app.css" /><link rel="stylesheet" href="BlazorSandbox.styles.css" /><link rel="icon" type="image/png" href="favicon.png" /><HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" /></head><body><Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" /><script src="_framework/blazor.web.js"></script></body></html>@code { protected override Task OnInitializedAsync() { Service.Foo = 123; return base.OnInitializedAsync(); }}Home.razor:
@page "/"@inject Service Service<PageTitle>Home</PageTitle><h1>Hello, world!</h1>Service.Foo: @Service.FooService.Foo is 0 here.
I've seen similar issues with scoped services getting initialized twice. These were related to prerendering though, which is already disabled in my case. Browsing a bit further through the documentation I could find the following info:
The App component is always rendered statically even if prerendering of a page component is disabled. Therefore, injecting services via the top-level imports file results in resolving two instances of the service in page components.
I am assuming this also applies to services resolved directly via @Inject. Is there any workaround for this? I need to initialize the service from a location where HttpContext is guaranteed to be available. AFAICT this is only the case for App.razor (formerly _Host.cshtml)?