Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor Page Unable to Call Service Method CS0120

I am using the service ITADService with the following method:

public async Task GetAllGames()
{
var result = InterpretStringResponse((await _http.GetAsync("api/itad")).ToString());
}

My razor page calls this method with:

protected override async Task OnInitializedAsync()
{
    await ITADService.GetAllGames();    
}

This leads to the CS0120 build-time error stating that an object reference is necessary, yet when I create an instance of the service on the page with:

private readonly HttpClient _http;
ITADService service = new ITADService(_http);

Visual Studio tells me that an initializer cannot reference it if it isn't static.

How is this supposed to be done? Is the error in the service or the page?

like image 763
Email User Avatar asked Sep 15 '25 09:09

Email User


1 Answers

How is this supposed to be done?

  1. Register the ITADService in Program.cs
    builder.Services.RegisterScoped<ITADService>();
  2. Inject the HttpClient in the constructor of ITADService
    public ITADService(HttpClient http) { _http = http; }
  3. Inject ITADService into your page
    @inject ITADService iTADService
like image 107
Henk Holterman Avatar answered Sep 17 '25 00:09

Henk Holterman