Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Why is scoped service injected in MainLayout.razor reinstanced? on every page

$
0
0

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:

  1. Why does this not work in MainLayout? Is it a different scope? Any other gotchas with this page?
  2. 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>

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>