I use to have a common service in MVC Application , register it as Transient service and access its value across whole application without any issue .
I tried to implement same mechanism inside my client side blazor app
First created a class AppState
public class AppState
{
public string BaseUrl { get; set; }
}
registered as a service
services.AddSingleton<AppState, AppState>();
Used in Blazor Component Index Component
public class IndexComponent : ComponentBase
{
[Inject]
HttpClient Http { get; set; }
[Inject]
public AppState AppState { get; set; }
protected override async Task OnInitializedAsync()
{
AppState = await Http.GetJsonAsync<AppState>(ConfigFiles.GetPath("appsettings.json"));
await Task.FromResult(0);
}
}
Tried to print base url in index.razor file
@page "/"
@inherits IndexComponent
<p>@AppState.BaseUrl</p>
Till Here its fine , now as it contain base url so i wanted to access it in another component
public class MiniCartComponent : ComponentBase
{
[Inject]
public AppState AppState { get; set; }
protected override async Task OnInitializedAsync()
{
await Task.FromResult(0);
}
}
Here it is empty , i dont know why
I tried to print it in razor file
@inherits MiniCartComponent
<p>@AppState.BaseUrl</p>
Here it is empty , it is registered as a service to share data across components , should not it have value across the app once it is set ??