I'm fairly new to Blazor and I want to use a 'GlobalSettings' class. I have tried using CascadingParameters but I'm getting null errors in the console even though the site is displaying fine. I suspect due to the order of loading components.
So I'd like to use DI and have the class populated during program.cs so I can ensure it's available by the time the components start rendering.
After digging around in searches, I have setup a singleton in program.cs and all the while I explicitly set the values in the class, I can see them when the class in injected (Obviously). However, I want to get the values from an API. So I have setup a GetRequiredService - Which I can see runs the API call I need and fills out and instance of gs. When I breakpoint on return gs; I can see the value has been updated as required. However this is not persisted when I inject the class into MainLayout.razor.
I have a feeling I'm made a very simple error but got to a point where I can't see the wood for the trees! Any help, advice, pointers greatly appreciated. Code below:
program.cs
var builder = WebAssemblyHostBuilder.CreateDefault(args);builder.RootComponents.Add<App>("#app");builder.RootComponents.Add<HeadOutlet>("head::after");builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.Configuration["API_Prefix"] ?? builder.HostEnvironment.BaseAddress) });builder.Services.AddSingleton<TestInject>();builder.Services.AddOptions();var host = builder.Build();var settingsService = host.Services.GetRequiredService<TestInject>();await settingsService.GetStuff();await builder.Build().RunAsync();TestInject Class:
public class TestInject{ public string TestItem { get; set; } = "Item A"; public TestInject() { }public async Task<TestInject> GetStuff() { var client = new ContentfulClient(new System.Net.Http.HttpClient(), SiteConfig.CONTENTFULAPIKEY, SiteConfig.CONTENTFULPREVIEWAPIKEY, SiteConfig.CONTENTFULSPACEID); var queryBuilder = QueryBuilder<Globals>.New.ContentTypeIs("transitionConfig"); var globalSettings = await client.GetEntries(queryBuilder); TestInject gs = new TestInject() { }; foreach(var item in globalSettings) { gs.TestItem = item.phase1Title; } return gs; <-- Actually sets TestItem to the correct value}}MainLayout:
@inject TestInject TestInject@code { Console.WriteLine(TestInject.TestItem); <-- Still says Item A}