Search code examples
c#razorblazor-webassembly

Injecting custom objects in Blazor WASM


I want to "delegate" my code responsible for communications with the backend API to a separate class which I want to inject into my Blazor components just like I inject the HttpClient. I create the separate class and registere it in Program.cs:

builder.Services.AddScoped<IBackendComms, BackendComms>();

And I inject it in a component:

@inject BackendComms backendComms

But when I do this I get the "Unhandled error" after starting the project.

How do I properly inject my custom classes in razor files?


Solution

  • In your razor component, inject the Interface instead of the class:

    @inject IBackendComms _backendComms
    

    Then you can call any method the interface has from your component's code:

    _backendComms.DoSomething(someParam);