Blazor FAQ - Dependency injection

Find answers for the most frequently asked questions
Expand All Collapse All

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.

Permalink

Dependency Injection is a technique for accessing services configured in a central location.

  • Blazor has built-in support for dependency injection (DI).
  • Users can use predefined services in their apps by directly injecting them in the components.
  • Blazor apps can also define custom services and make them available via DI.

Blazor has a special base component called OwningComponentBase. For example, a component is created by the user by extending the OwningComponentBase will have special controls over injected services and ensure their proper disposal when a component is destroyed. Users can create custom services and use those services in the entire application. To do so, the custom services need to be added to the startup.cs (server side) and to program.cs (client-side Blazor) as either a singleton or scoped service.

[startup.cs]
public class Startup {

     public void ConfigureServices(IServiceCollection services)
    {
           .....
           .....
           services.AddScoped<Custom_ServiceName>();
    }
}
[program.cs]

public class Program
{
        public static async Task Main(string[] args)
        {
            ……
            builder.Services.AddSingleton<Custom_Service_Name>();
        }
}

For more information, please refer here.

Permalink

Share with

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

Please submit your question and answer.