Author : MD TAREQ HASSAN | Updated : 2020/07/24
Dependency in blazor
- Blazor supports DI
- Apps can use built-in services by injecting them into components
@inject
: DI in razor syntax (inxxx.razor
file)[Inject]
: DI in code behind file (i.e.xxx.razor.cs
file)- Apps can also define and register custom services and make them available throughout the app via DI
- Default services are automatically added to the app’s service collection.
- Links:
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();
}
}