Transfer service is the preferred technique when all of your components use the same data. In this tutorial, you will discover:
You can download the example code used in this topic on GitHub.
Transfer service class is a like a model with properties and events for each property.
public class ExampleTransferService
{
private string _data = "Blazor School";
public string Data
{
get => _data;
set
{
_data = value;
DataChanged?.Invoke(this, value);
}
}
public event EventHandler<string> DataChanged = (sender, value) => { };
public ObservableCollection<ExampleClass> ExampleInstances { get; set; } = new();
}
In the code sample, we have Data and ExampleInstances as a demonstration for a property and a collection. For collections, you can either use ObservableCollection or create your own Collection<T> class.
List does not support hooking events.
Program.cs. For example:...
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped<ExampleTransferService>();
You can consume a transfer service in a component or a class. To consume a transfer service in a class, you need to inject the service into the constructor of your class and register it as the same as the transfer service class. In this tutorial, we will focus on consuming a transfer service in a component.
IDisposable interface at the directive section of your component. For example:@inject ExampleTransferService ExampleTransferService @implements IDisposable
DataChanged event which has EventHandler<string> as the event handler, you need to have the method with object? sender, string value as the method signature. See the following code:@code {
...
public void OnDataClassChanged(object? sender, string value)
{
InvokeAsync(StateHasChanged);
}
}
@code {
...
protected override void OnInitialized()
{
ExampleTransferService.ExampleInstances.CollectionChanged += OnCollectionChanged;
ExampleTransferService.DataChanged += OnDataClassChanged;
}
public void Dispose()
{
ExampleTransferService.ExampleInstances.CollectionChanged -= OnCollectionChanged;
ExampleTransferService.DataChanged -= OnDataClassChanged;
}
}