Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make MauiBlazorBindingsRenderer a singleton #100

Merged
merged 1 commit into from
Jan 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/BlazorBindings.Core/NativeComponentRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorBindings.Core
Expand All @@ -15,6 +16,7 @@ public abstract class NativeComponentRenderer : Renderer
private readonly Dictionary<int, NativeComponentAdapter> _componentIdToAdapter = new Dictionary<int, NativeComponentAdapter>();
private ElementManager _elementManager;
private readonly Dictionary<ulong, Action<ulong>> _eventRegistrations = new Dictionary<ulong, Action<ulong>>();
private readonly List<(int Id, IComponent Component)> _rootComponents = new();


public NativeComponentRenderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
Expand Down Expand Up @@ -63,6 +65,8 @@ public async Task<IComponent> AddComponent(Type componentType, IElementHandler p
var component = InstantiateComponent(componentType);
var componentId = AssignRootComponentId(component);

_rootComponents.Add((componentId, component));

var rootAdapter = new NativeComponentAdapter(this, closestPhysicalParent: parent, knownTargetElement: parent)
{
Name = $"RootAdapter attached to {parent.GetType().FullName}",
Expand All @@ -75,15 +79,23 @@ public async Task<IComponent> AddComponent(Type componentType, IElementHandler p
return component;
}).ConfigureAwait(false);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
HandleException(ex);
return null;
}
}

/// <summary>
/// Removes the specified component from the renderer, causing the component and its
/// descendants to be disposed.
/// </summary>
public void RemoveRootComponent(IComponent component)
{
var componentId = _rootComponents.LastOrDefault(c => c.Component == component).Id;
RemoveRootComponent(componentId);
}

protected override Task UpdateDisplayAsync(in RenderBatch renderBatch)
{
HashSet<int> processedComponentIds = new HashSet<int>();
Expand Down
2 changes: 1 addition & 1 deletion src/BlazorBindings.Maui/MauiAppBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static MauiAppBuilder UseMauiBlazorBindings(this MauiAppBuilder builder)
builder.Services
.AddSingleton<Navigation>(svcs => new Navigation(svcs))
.AddSingleton<INavigation>(services => services.GetRequiredService<Navigation>())
.AddScoped<MauiBlazorBindingsRenderer>(svcs => new MauiBlazorBindingsRenderer(svcs, svcs.GetRequiredService<ILoggerFactory>()));
.AddSingleton<MauiBlazorBindingsRenderer>(svcs => new MauiBlazorBindingsRenderer(svcs, svcs.GetRequiredService<ILoggerFactory>()));

return builder;
}
Expand Down
2 changes: 1 addition & 1 deletion src/BlazorBindings.Maui/MauiBlazorBindingsRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async Task<TComponent> AddComponentLocal()

if (!elementsComponentTask.IsCompleted && parent is MC.Application app)
{
// MAUI requires the Application to have the MainPage. If rendering task is not completed synchroniously,
// MAUI requires the Application to have the MainPage. If rendering task is not completed synchronously,
// we need to set MainPage to something.
app.MainPage ??= new MC.ContentPage();
}
Expand Down
13 changes: 7 additions & 6 deletions src/BlazorBindings.Maui/Navigation/Navigation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,23 +109,24 @@ public Task<T> BuildElement<T>(RenderFragment renderFragment) where T : Element
[EditorBrowsable(EditorBrowsableState.Never)]
public async Task<T> BuildElement<T>(Type componentType, Dictionary<string, object> arguments) where T : Element
{
var scope = _services.CreateScope();
var serviceProvider = scope.ServiceProvider;
var renderer = serviceProvider.GetRequiredService<MauiBlazorBindingsRenderer>();
var renderer = _services.GetRequiredService<MauiBlazorBindingsRenderer>();

var element = (Element)(await renderer.GetElementFromRenderedComponent(componentType, arguments)).Element;
var (bindableObject, componentTask) = await renderer.GetElementFromRenderedComponent(componentType, arguments);
var element = (Element)bindableObject;

element.ParentChanged += DisposeScopeWhenParentRemoved;

return element as T
?? throw new InvalidOperationException($"The target component of a navigation must derive from the {typeof(T).Name} component.");

void DisposeScopeWhenParentRemoved(object _, EventArgs __)
async void DisposeScopeWhenParentRemoved(object _, EventArgs __)
{
if (element.Parent is null)
{
scope.Dispose();
element.ParentChanged -= DisposeScopeWhenParentRemoved;

var component = await componentTask;
renderer.RemoveRootComponent(component);
}
}
}
Expand Down