Dependability injection is a kind of design pattern that assists in creating a loosely coupled application design. Testability, greater maintainability, and reusability are provided by it. The dependencies required for completing the task are provided from the outer world instead of the ones created inside the class in this pattern. There are several ways for injecting the dependencies, namely constructor, setter, and interface-based injection.
Both Blazor Server and Blazor Webassembly App support Dependency. As Blazor provides built-in services you can also build a custom service and use it with a compliment while injecting via DI.
Defining our dependency
You are required to create a dependency before injecting it. You can use the age-old ToDo example but do not worry about creating a ToDo application.
Firstly you should create a basic ToDo class.
public class ToDo { public int Id { get; set; } public string Title { get; set; } public bool Completed { get; set; } }
Now you will create a class required by a blazer page or component. There will be an API that will be retrieving ToDo items with the service in cases like this. You will not be called a server. Else you will be simply returning some mock data.
Registering injectable dependencies
One of the things that a blazer application performs while running through its startup code is configuring a dependency injection container. It is responsible for generating instances of classes. You are required to register which classes you wished to make available to inject dependencies wild is bootstrapping process automatically. You can also register a class itself as injectable:
services.AddSingleton<ToDoApi>();
As long as you will be additionally specifying the class that will be implementing the interface service, you can register and interface as injectable.
service.AddSingeton<IToDoApi, ToDoApi>();
Service lifetime
Services configure the Blazor app within a specific service lifetime. Usually, three lifetimes exist as Blazor doesn’t support scoped, singleton, and transient instead it supports all three lifetimes. The majority of them are supported in the Blazor server app, and some in the Blazor web assembly app. Following is a list of the service lifetimes:
Scoped
The service instance is not supported in the Blazor web assembly app as it is created per request. Scope of the service is per connection in the Blazor server app source code services may behave like a singleton service.
Singleton
The service instances through the application life are created and shared by it. It is supported by both the Blazor server and web assembly app.
Transient
The service instance is created whenever requested.
Built-in services
Built-in services also referred to as the Blazor, provides framework services. The framework services can be added automatically in the app’s service connection with a service predefined lifetime. Here are the framework services:
HttpClient
It could be understood as a method used for sending or receiving http requests/responses provided by this service. Also could also be added as a singleton service in the Blazor server app.
IJSRuntime
The service provides a method for JavaScript intercrop call. The single service is created and shared as per the application in the Blazor web assembly app, and the service instance is created and shared as per the bond in the blazer server app.
NavigationManager
a method for working with URI and navigation state is provided by the service. The single instance of service is created and shared as per the Blazor web assembly app. According to the connection in the Blazor server app, the service instance is created and shared.
Register customer service.
This service is offered in asp.net core Blazor and is a simple class that contains specific methods. For using custom service in components, you must first register custom service in the startup class’s configure services method. A list of service descriptor objects and customer service is required to be added into the service collection by using the “Add{lifetime} method” is contained by the Iservice collection.
For instance, the service is added as a singleton lifetime in the service collection using the add singleton method.
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IHelloWorldService, HelloWorldService>(); services.AddSingleton<ComplexService>(); }
Inject service into a component
By using @injectdirective for injecting attributes, you can easily inject uses into the component. You could also inject multiple different services by using multiple @inject directives.
Syntax
@inject ServiceType ServiceInstanceName HelloWorldService is injected into a component by using @inject directive in the following example, @page "/test data" @inject IHelloWorldService HelloWorldService ... @code { private string name; protected override async Task OnInitializedAsync() { name = HelloWorldService.GetName(); ... ... } }
You could also inject a service into the components code behind for class-only components using the inject attribute. Service is injected into the components code by using the injured attribute in the following example.
Namespace BlazorWebAssemblyApp.Pages { using BlazorWebAssemblyApp.Service; using Microsoft.AspNetCore.Components; public class EmployeeComponent : ComponentBase { [Inject] protected IHelloWorldService helloWorldService { get; set; } } }
But the services are not registered with the service container, the Blazor component is unable to find services, and the Blazor framework raises an exception.
Customer service may need to use additional service resources, and you can inject the additional services as dependency injection. It would help if you used the constructor injection. The required services up automatically are combined in a parameter where the service instance is created. It is not allowed to use attributes for injecting service dependency with another service.
The HttpClientdefault service is injected into the complex service in the example stated below.
public class ComplexService { public ComplexService(HttpClient httpClient) { } public string GetName() { return "Jignesh Trivedi"; } }
End words
You are allowed to create a loosely coupled application to provide greater maintainability, testability, and usability by dependency injection. There is also built-in support of dependency injection in Blazor. It was all about how you can inject and use a DI service in the Blazor app and component.