The component should keep a reference to the DotNetObjectReference
we create.
The component should implement IDisposable
and dispose our DotNetObjectReference
.
@page "/" @inject IJSRuntime JSRuntime @implements IDisposable <h1>Text received</h1> <ul> @foreach (string text in TextHistory) { <li>@text</li> } </ul> @code { List<string> TextHistory = new List<string>(); DotNetObjectReference<Index> ObjectReference; protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); if (firstRender) { ObjectReference = DotNetObjectReference.Create(this); await JSRuntime.InvokeVoidAsync("BlazorUniversity.startRandomGenerator", ObjectReference); } } [JSInvokable("AddText")] public void AddTextToTextHistory(string text) { TextHistory.Add(text.ToString()); while (TextHistory.Count > 10) TextHistory.RemoveAt(0); StateHasChanged(); System.Diagnostics.Debug.WriteLine("DotNet: Received " + text); } public void Dispose() { GC.SuppressFinalize(this); if (ObjectReference != null) { //Now dispose our object reference so our component can be garbage collected ObjectReference.Dispose(); } } }
var BlazorUniversity = BlazorUniversity || {}; BlazorUniversity.startRandomGenerator = function (dotNetObject) { return setInterval(function () { let text = Math.random() * 1000; console.log("JS: Generated " + text); dotNetObject.invokeMethodAsync('AddText', text.toString()); }, 1000); }; BlazorUniversity.stopRandomGenerator = function (handle) { clearInterval(handle); };
References
https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-dotnet-from-javascript?view=aspnetcore-6.0#class-instance-examples
https://blazor-university.com/javascript-interop/calling-dotnet-from-javascript/
https://blazor-university.com/javascript-interop/calling-dotnet-from-javascript/lifetimes-and-memory-leaks/