I am very new to Blazor and I am just trying to create a basic CRUD app that calls an API.
The error I’m getting is:
InvalidOperationException: Cannot provide a value for property
‘peopleService’ on type ‘PeopleUI.Client.Pages.People.PeopleList’.
There is no registered service of type
‘PeopleUI.Client.Services.IPeopleService’.
this is my program.cs file in the client project
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using PeopleUI.Client.Services;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddHttpClient("api", client =>
{
client.BaseAddress = new Uri("http://localhost:5000");
});
builder.Services.AddSingleton<IPeopleService, PeopleService>();
await builder.Build().RunAsync();
this is my service:
public interface IPeopleService
{
Task<IEnumerable<Person>> GetPeopleAsync();
Task<Person?> GetPersonById(Guid id);
Task<bool> AddPerson(Person person);
Task DeletePerson(Guid id);
Task<bool> UpdatePerson(Person person);
}
public class PeopleService(IHttpClientFactory factory) : IPeopleService
{
public async Task<IEnumerable<Person>> GetPeopleAsync()
{
using var client = factory.CreateClient("api");
var respose = await client.GetAsync("/people");
var people = await respose.Content.ReadFromJsonAsync<IEnumerable<Person>>();
return people;
}
public async Task<Person?> GetPersonById(Guid id)
{
using var client = factory.CreateClient("api");
var respose = await client.GetAsync($"/people/{id}");
return await respose.Content.ReadFromJsonAsync<Person>();
}
public async Task<bool> AddPerson(Person person)
{
using var client = factory.CreateClient("api");
var content = GetContent(person);
var respose = await client.PostAsync("/people", content);
return respose.IsSuccessStatusCode;
}
private static StringContent GetContent(Person person)
{
var content = new StringContent(JsonConvert.SerializeObject(person),
Encoding.UTF8,
MediaTypeNames.Application.Json);
return content;
}
public async Task DeletePerson(Guid id)
{
using var client = factory.CreateClient("api");
await client.DeleteAsync($"/people/{id}");
}
public async Task<bool> UpdatePerson(Person person)
{
using var client = factory.CreateClient("api");
var content = GetContent(person);
var respose = await client.PutAsync($"/people/{person.Id}",content);
return respose.IsSuccessStatusCode;
}
}
and this is my view:
@page "/people-list"
@using PeopleUI.Client.Services
@using PeopleUI.Client.Models
@inject IPeopleService peopleService
<h3>PeopleList</h3>
<table>
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Email</th>
</tr>
@if (People is not null)
{
@foreach (var person in People)
{
<tr>
<td>@person.LastName</td>
<td>@person.FirstName</td>
<td>@person.Email</td>
</tr>
}
}
</thead>
</table>
@code {
private IEnumerable<Person>? People { get; set; }
protected override async Task OnInitializedAsync()
{
People = await peopleService.GetPeopleAsync();
}
}
Can someone help me figure out why i am getting this error as you can see i am registering IPeopleService