Blazor FAQ - Dependency injection

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

For more information, refer to this link.

Permalink
What is Dependency Injection (DI) in Blazor?

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
Error: System.ArgumentException: Cannot instantiate implementation type ‘Microsoft.AspNetCore.Blazor.Services.UriHelperBase’ for service type ‘Microsoft.AspNetCore.Blazor.Services.IUriHelper’. Now what?

Here is the solution.

This works after adding a dependency injection for NavigationManager, and IUriHelper has been replaced with NavigationManager.

@inject NavigationManager Navigation;

Reference link:

https://devblogs.microsoft.com/aspnet/asp-net-core-and-blazor-updates-in-net-core-3-0-preview-9/

Permalink