0

My Index page has the @code block calling a service method:

@using BlazingPizza.Services

@inject PizzaService PizzaService

...

@code {
    private List<Pizza> specials = new List<Pizza>();

    protected override async Task OnInitializedAsync()
    {
        specials = await PizzaService.GetPizzasAsync();
    }
}

The service is already registered in Program.cs:

builder.Services.AddSingleton<PizzaService>();

I also tried injecting the interface and declaring the following:

builder.Services.AddSingleton<IPizzaService, PizzaService>();

But whenever I call GetPizzasAsync, the exception happens.

NullReferenceException: Object reference not set to an instance of an object.
BlazingPizza.Pages.Index.OnInitializedAsync() in Index.razor
+
        specials = await PizzaService.GetPizzasAsync();

What am I missing? I am following official's tutorials.

  • Try out to put breakpoint in your method and find what is null there – Serhii Feb 06 '22 at 18:31
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – marc_s Feb 06 '22 at 19:04
  • The code you have posted looks largely OK. So it is in some other part... – H H Feb 06 '22 at 19:14
  • Remove all the markup code and try again. Post a full stack trace and a complete page if you need more help. – H H Feb 06 '22 at 19:15

1 Answers1

0

Use builder.Services.AddSingleton<IPizzaService, PizzaService>(); but inject the Interface instead of the Class:

@inject IPizzaService PizzaService

Now PizzaService is implemented correctly and the GetPizzaAsync() method can be used to populate your specials list.

jmon12
  • 1,090
  • 8
  • 17
KenNipper
  • 11
  • 3