Synchronous IDisposable
@implements IDisposable ... @code { ... public void Dispose() { obj?.Dispose(); } }
Asynchronous IAsyncDisposable
@implements IAsyncDisposable ... @code { ... public async ValueTask DisposeAsync() { if (obj is not null) { await obj.DisposeAsync(); } } }
Event handlers
Always unsubscribe event handlers from .NET events.
@implements IDisposable <EditForm EditContext="@editContext"> ... <button type="submit" disabled="@formInvalid">Submit</button> </EditForm> @code { ... private EventHandler<FieldChangedEventArgs>? fieldChanged; protected override void OnInitialized() { editContext = new(model); fieldChanged = (_, __) => { ... }; editContext.OnFieldChanged += fieldChanged; } public void Dispose() { editContext.OnFieldChanged -= fieldChanged; } }
References
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-6.0#synchronous-idisposable
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-6.0#asynchronous-iasyncdisposable
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-6.0#event-handlers
https://www.syncfusion.com/faq/blazor/components/how-can-i-properly-dispose-a-component-in-blazor