Author : MD TAREQ HASSAN | Updated : 2020/07/24

Dependency in blazor

Register service

Blazor WebAssembly

Program.cs

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
		
        builder.Services.AddSingleton<IDataAccess, DataAccess>();
		
        builder.RootComponents.Add<App>("app");

        await builder.Build().RunAsync();
    }
}

Blazor server

Startup.cs

public class Startup
{
	// ... ... ...

	public void ConfigureServices(IServiceCollection services)
	{
	
		// ... ... ...
		
		services.AddSingleton<IDataAccess, DataAccess>();
		
		// ... ... ...
	}

	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		// ... ... ...
	}
}

Use in component

Code behind

public class MyComponentBase : ComponentBase
{
    // DI works even if using the InjectAttribute in a component's base class.
    [Inject]
    protected IDataAccess DataRepository { get; set; }
	
    //... ... ...
}
@page "/demo"
@inherits MyComponentBase

<!-- html here -->

Mixed code

@page "/customer-list"
@using Services
@inject IDataAccess DataRepository

<!-- html here -->

@code {

    private IReadOnlyList<Customer> customers;

    protected override async Task OnInitializedAsync()
    {
        customers = await DataRepository.GetAllCustomersAsync();
    }
}