I have the following class which I use to get and set a token in browser local storage:
StateService.cs
using Microsoft.AspNetCore.Components;using Microsoft.JSInterop;namespace Web.Services{ public class StateService { private IJSRuntime jsRuntime; public StateService(IJSRuntime _jsRuntime) { jsRuntime = _jsRuntime; } public async Task<string> getToken() { var token = await jsRuntime.InvokeAsync<string>("localStorage.getItem", "token"); return token; } public async Task setToken(string token) { await jsRuntime.InvokeVoidAsync("localStorage.setItem", "token", token); } }}I then register this as a singleton in the main Program.cs
Program.cs:
builder.Services.AddSingleton<StateService>();builder.Services.AddScoped<ITestService>(s =>{ var httpClient = new HttpClient(); var token = ""; var baseUrl = "http://localhost:4000"; return new TestService(httpClient, token, baseUrl);});However, I need to access an instance of StateService so I can pass the token to the TestService above.
I tried:
var stateService = new StateService();but of course it is expecting an instance for IJSRuntime. .NET seems to take care of it when using AddSingleton, but not sure how to correctly instantiate the StateService manually in the Program.cs file.
Please note that I do not want to pass stateService itself as a parameter to test service because Test Service is completely decoupled from the playform it is running on, therefore it is not aware of how or where the token comes from, only that it has a token to work with.
So either I need to access the StateService class itself in Program.cs which IJSRuntime being instantiated or instantiate IJSRuntime itself in Program.cs
Is this possible or am I going about this the wrong way?