Live Chat Icon For mobile
Live Chat Icon

How do you add dependency injection in Blazor?

Platform: Blazor| Category: Dependency injection

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");
    }
}

For more information, refer to this link.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.