Dependency in blazor

Blazor server

Register service

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; }
	
    //... ... ...
}

Usage

@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();
    }
}

Blazor WebAssembly

Program.cs

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

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