Blazor

How do you add dependency injection in Blazor?

How do you add dependency injection in Blazor?

Use the @inject directive to inject the service into components. @inject has two parameters (type and name). Type represents the service type and name represents the service instance name.

Syntax:

@inject ServiceType ServiceInstanceName

In the following example, we have injected the dependency IJSRuntime service, which is used for handling JavaScript interoperability to invoke a JavaScript function during a button click in Blazor.

[index.razor]

@page "/"
@inject IJSRuntime jsRuntime

<h3>Index Page</h3>

<button @onclick="SomeFunctionCall">Click Me...!!!</button>

@code {
    public async Task SomeFunctionCall()
    {
        await jsRuntime.InvokeAsync("jsFunction");
    }
}

I would suggest you check the below link for better understanding:
https://docs.microsoft.com/en-us/aspnet/core/blazor/dependency-injection

 

Sumitra Kumari Shaw

An Engineering graduate who Enjoys building things that live on the internet.