Understanding Dependency Injection
DI is a technique in which an object accesses services that have been configured in a central location. The central location is the DI container. When using DI, each consuming class does not need to create its own instance of the injected class that it has a dependency on. It is provided by the framework and is called a service. In a Blazor WebAssembly application, the services are defined in the program.cs
file.
We have already used DI in this book with the following services:
- HttpClient
- IJSRuntime
- NavigationManager
DI container
When a Blazor WebAssembly application starts, it configures a DI container. The DI container is responsible for building the instances of the service and lives until the user closes the tab in their browser that is running the web app. In the following example, the CartService
implementation is registered for ICartService
:
builder.Services.AddSingleton<ICartService, CartService>();
After a service has been added to...