I wanted to create a data store that was accessible between different pages on the site. On every page I want the same code to run. Rather than putting it on every page I figured it would be best to put it into MainLayout.razor so I can just edit it there in the one spot.
However each page has a new instance of the scoped data, and its not being shared.
If I take the code and manually insert it on each page then it works fine.
My questions are:
- Why does this not work in
MainLayout? Is it a different scope? Any other gotchas with this page? - What is the best way to have the same code run on every page without manually adding it?
This is a Server project (not WASM)
I tried:
in Program.cs :builder.Services.AddScoped<ScopedDataStore>();in MainLayout.razor:@inject ScopedDataStore ScopedData@inject NavigationManager _nav...protected override async Task OnInitializedAsync(){ ScopedData.SetCurrentUrl(_nav.Uri);}and ScopedDataStore:public class ScopedDataStore{ private string CurrentUrl=""; private string PreviousUrl=""; public void SetCurrentUrl(string x) { PreviousUrl = CurrentUrl; CurrentUrl = x; } public string GetLastUrl() { return this.GetHashCode().ToString(); }}This is in MainLayout.razor:
<article class="content px-4"> @Body<h1>Last URL : @ScopedData.GetLastUrl()</h1</article>