-
Book Overview & Buying
-
Table Of Contents
Blazor WebAssembly by Example - Third Edition
By :
Dependency Injection (DI) lets Blazor components use services without creating them manually. Services are configured centrally in the DI container and provided by the framework. In a Blazor WebAssembly app, the services are defined in the Program.cs file.
You have already used DI in this book with the following built-in services:
HttpClientIJSRuntimeNavigationManagerOn startup, Blazor WebAssembly configures the DI container. The DI container is responsible for creating service instances and lives until the browser tab closes. In the following example, the CartService implementation is registered for ICartService:
builder.Services.AddSingleton<ICartService, CartService>();
After a service is registered in the DI container, the @inject directive is used to inject it into a component by specifying the service type and the property name to assign it to: