I have a blazor component that will be reused, the parameters in it will point to specific endpoints that are specified when the component is created. These components all need to be polling data constantly (every few seconds) as the API that I’m calling does not support streaming data. I’m having a hard time implementing this into my project, I’m trying to use IHostedService
that consumes a separate scoped service that reaches out to the api specified by the respective component. But all of the docs I’ve seen from Microsoft and examples online show them doing something trivial like printing, nothing being returned. Is this the right way to go about doing this? I’ve gotten this to work by just setting up a timer in the .razor page and making the scoped service a singleton. However, once the service is scoped I get the exception “Cannot access a disposed object” on the httpclient.
.razor component code
protected override async Task OnInitializedAsync()
{
// Set up polling every 5 seconds
timer = new Timer(async _ => await FetchData(), null, 0, 5000);
}
private async Task FetchData()
{
variable = await scopedservice.GetData(info);
await InvokeAsync(() => StateHasChanged());
}
Scoped service
public async Task<Data> GetData(string info)
{
try
{
return await _httpClient.GetFromJsonAsync<Data>($"{info}");
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return default;
}
}
Program.cs
builder.Services.AddHttpClient();
builder.Services.AddScoped<IScopedService, ScopedService>();