diff --git a/docs/design/HandlerResolution.md b/docs/design/HandlerResolution.md index 93a5e1db85a3..98b29ee81fca 100644 --- a/docs/design/HandlerResolution.md +++ b/docs/design/HandlerResolution.md @@ -14,6 +14,22 @@ builder.ConfigureMauiHandlers(handlers => } ``` +## Handler Instantiation + +How a handler instance is created depends on how it was resolved: + +- **DI-registered handlers**: Instantiated through `MauiFactory.GetService()`, which uses `Activator.CreateInstance` on the registered `ImplementationType`, or invokes the `ImplementationFactory` delegate if one was provided. Factory delegates receive a service provider for the current `IMauiContext`, so they can resolve that context (and, on Android, its `Context`). +- **`[ElementHandler]` attribute**: The internal attribute requires a public parameterless constructor and creates the handler directly — no DI involvement. +- **Constructor injection**: `ElementExtensions.ToHandler()` delegates activation to the internal `MauiHandlersFactory.GetHandlerWithInjection()` path. The built-in factory checks whether the resolved handler type has a public parameterless constructor. If it does, `Activator.CreateInstance` is used; otherwise, `ActivatorUtilities.CreateInstance` supplies constructor arguments from the current context's DI container (including its Android `Context`) without first throwing a missing-constructor exception. Value-type handlers retain their default construction through `Activator.CreateInstance`. A failure to resolve a dependency propagates without retrying the activation. Custom `IMauiHandlersFactory` implementations retain the exception-based fallback for `MissingMethodException`, including when wrapped in `HandlerNotFoundException`. + +Constructor selection is checked on each activation, so no process-wide activation-strategy cache or separate invalidation is needed. Handler resolution still runs first on every request, and factory delegates are never bypassed. Each activation resolves dependencies from the current context, and separately built `MauiApp` instances do not affect one another. A handler type that needs constructor injection is never retained as a singleton: even when registered with a singleton descriptor, each activation creates a new handler from the current context's dependencies, as before. Handler types created through factory delegates and constructor injection are recorded when activated, so Hot Reload handler replacement applies to them. + +> **Note:** Direct `GetHandler()` callers keep the parameterless-constructor behavior: a registered handler type +> without a public parameterless constructor throws `MissingMethodException`. Declaring handlers with a +> parameterless constructor (and registering an implementation factory with +> `AddHandler(Func)` when constructor arguments are required) +> remains the recommended approach. + ## Types used in the resolution of Handlers to Views ### `MauiFactory` @@ -31,8 +47,7 @@ public class MauiHandlersFactory : MauiFactory, IMauiHandlersFactory #### Features of the `MauiFactory` - Handler registration can theoretically happen at any time because it happens via the `IMauiHandlerFactory`. All you have to do is grab the `IMauiHandlersCollection` from `IMauiHandlerFactory` and add an additional Handler. This isn't a common use case but we do make use of this feature [here](https://github.com/dotnet/maui/blob/main/src/Controls/samples/Controls.Sample/Controls/BordelessEntry/BordelessEntryServiceBuilder.cs#L41). - `MauiFactory` allows you to register two types that have no relationship with each other. `Button` and `ButtonHandler` don't implement any of the same interfaces, `Button` isn't the "Concrete Implementation" of `ButtonHandler`. -- `MauiFactory` has support for `ctor` resolution but we currently have it disabled in all cases. - - Handlers will currently attempt to instantiate through [Extensions.DependencyInjection.ActivatorUtilities.CreateInstance](https://github.com/dotnet/maui/blob/cc53f0979baf5d6bb8a5d6bf84b64f3cf591c56f/src/Core/src/Platform/ElementExtensions.cs#L34 ) if a default constructor hasn't been created. So the ctor resolution feature of `MauiFactory` probably doesn't have any currently useful purpose. +- `MauiFactory` creates type-based registrations through a virtual activation hook. `MauiHandlersFactory` overrides that hook for context-aware activation through `ToHandler()`, selecting constructor injection when no public parameterless constructor exists. Public `GetHandler()` calls continue to require a parameterless constructor for type-based registrations. - `MauiFactory` currently doesn't support Scoped Services which is the main reason why we switched to `Ms.Ext.DI` for our main implementation. .NET MAUI Blazor requires Scoped Services and we've started using Scoped Services as well for multi-window. - `MauiFactory` retrieves all base types from the requested type and all implemented interfaces. It first iterates over base types and then if nothing is found it loops through the interfaces. The interface behavior currently leads to some odd behavior because everything implements `IView`. This means that if a handler isn't registered then `MauiFactory` just returns a random handler because technically every single handler is registered against a cross platform view that implements`IView`. https://github.com/dotnet/maui/issues/1298 - We should probably remove the interface matching part of `MauiFactory` diff --git a/src/Core/src/Hosting/Internal/MauiFactory.cs b/src/Core/src/Hosting/Internal/MauiFactory.cs index fe5f8bd2b2ad..bee7cb99e0dd 100644 --- a/src/Core/src/Hosting/Internal/MauiFactory.cs +++ b/src/Core/src/Hosting/Internal/MauiFactory.cs @@ -50,7 +50,7 @@ public MauiFactory(IMauiServiceCollection collection) return typeInstance; } - static object? CreateInstance(ServiceDescriptor item, IServiceProvider implementationFactoryServiceProvider) + protected virtual object? CreateInstance(ServiceDescriptor item, IServiceProvider implementationFactoryServiceProvider) { if (item.ImplementationType != null) { diff --git a/src/Core/src/Hosting/Internal/MauiHandlersFactory.cs b/src/Core/src/Hosting/Internal/MauiHandlersFactory.cs index a7fcb7c20ff5..323eacd0884d 100644 --- a/src/Core/src/Hosting/Internal/MauiHandlersFactory.cs +++ b/src/Core/src/Hosting/Internal/MauiHandlersFactory.cs @@ -24,6 +24,82 @@ public MauiHandlersFactory(IMauiHandlersCollection collection) internal IElementHandler? GetHandler(Type type, IMauiContext mauiContext) => GetHandler(type, new HandlerActivationServiceProvider(this, mauiContext)); + internal static IElementHandler? GetHandlerWithInjection(IMauiHandlersFactory handlers, Type viewType, IMauiContext mauiContext) + { + var activationServices = handlers is MauiHandlersFactory factory + ? new HandlerActivationServiceProvider(factory, mauiContext, useConstructorInjection: true) + : null; + try + { + if (activationServices is not null && handlers is MauiHandlersFactory handlersFactory) + return handlersFactory.GetHandler(viewType, activationServices); + + return handlers.GetHandler(viewType, mauiContext); + } + catch (MissingMethodException) when (activationServices?.ConstructorInjectionAttempted != true) + { + return CreateTypeWithInjection(handlers, viewType, mauiContext); + } + catch (HandlerNotFoundException ex) when (ex.InnerException is MissingMethodException + && activationServices?.ConstructorInjectionAttempted != true) + { + return CreateTypeWithInjection(handlers, viewType, mauiContext); + } + } + + protected override object? CreateInstance(ServiceDescriptor item, IServiceProvider implementationFactoryServiceProvider) + { + if (item.ImplementationType is Type handlerType + && typeof(IElementHandler).IsAssignableFrom(handlerType) + && implementationFactoryServiceProvider is HandlerActivationServiceProvider { UseConstructorInjection: true } provider + // MauiFactory retains singleton instances, so a handler built from one context's dependencies would be + // shared by every element and context. Such registrations keep the base activation; when it throws + // MissingMethodException, GetHandlerWithInjection injects a new handler on each request. + && item.Lifetime != ServiceLifetime.Singleton) + return CreateHandlerInstance(handlerType, provider); + + return base.CreateInstance(item, implementationFactoryServiceProvider); + } + + static IElementHandler CreateHandlerInstance( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type handlerType, + HandlerActivationServiceProvider? activationServices) + { + if (activationServices is null) + return (IElementHandler)Activator.CreateInstance(handlerType)!; + + if (handlerType.IsValueType || handlerType.GetConstructor(Type.EmptyTypes) is not null) + return (IElementHandler)Activator.CreateInstance(handlerType)!; + + // A dependency failure must propagate without retrying the entire injection. + activationServices.ConstructorInjectionAttempted = true; + return CreateTypeWithInjection(handlerType, activationServices.MauiContext); + } + + static IElementHandler? CreateTypeWithInjection(IMauiHandlersFactory handlers, Type viewType, IMauiContext mauiContext) + { + var handlerType = handlers.GetHandlerType(viewType); + + if (handlerType == null) + return null; + + return CreateTypeWithInjection(handlerType, mauiContext); + } + + static IElementHandler CreateTypeWithInjection( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type handlerType, + IMauiContext mauiContext) + { +#if ANDROID + if (mauiContext.Context != null) + { + return (IElementHandler)ActivatorUtilities.CreateInstance(mauiContext.Services, handlerType, mauiContext.Context); + } +#endif + + return (IElementHandler)ActivatorUtilities.CreateInstance(mauiContext.Services, handlerType); + } + IElementHandler? GetHandler(Type type, IServiceProvider implementationFactoryServiceProvider) { if (TryGetVirtualViewHandlerServiceType(type) is Type serviceType @@ -90,12 +166,17 @@ sealed class HandlerActivationServiceProvider : IServiceProvider readonly MauiHandlersFactory _handlerServices; readonly IMauiContext _mauiContext; - public HandlerActivationServiceProvider(MauiHandlersFactory handlerServices, IMauiContext mauiContext) + public HandlerActivationServiceProvider(MauiHandlersFactory handlerServices, IMauiContext mauiContext, bool useConstructorInjection = false) { _handlerServices = handlerServices; _mauiContext = mauiContext; + UseConstructorInjection = useConstructorInjection; } + public IMauiContext MauiContext => _mauiContext; + public bool UseConstructorInjection { get; } + public bool ConstructorInjectionAttempted { get; set; } + public object? GetService(Type serviceType) { if (serviceType == typeof(IServiceProvider)) @@ -118,6 +199,9 @@ public HandlerActivationServiceProvider(MauiHandlersFactory handlerServices, IMa static class MauiHandlersFactoryExtensions { + internal static IElementHandler? GetHandlerWithInjection(this IMauiHandlersFactory handlers, Type type, IMauiContext mauiContext) => + MauiHandlersFactory.GetHandlerWithInjection(handlers, type, mauiContext); + internal static IElementHandler? GetHandler(this IMauiHandlersFactory handlers, Type type, IMauiContext mauiContext) => handlers is MauiHandlersFactory handlersFactory ? handlersFactory.GetHandler(type, mauiContext) diff --git a/src/Core/src/HotReload/HotReloadHelper.cs b/src/Core/src/HotReload/HotReloadHelper.cs index 6d6cc46c72e1..429ab7e586f0 100644 --- a/src/Core/src/HotReload/HotReloadHelper.cs +++ b/src/Core/src/HotReload/HotReloadHelper.cs @@ -213,17 +213,14 @@ internal static void RegisterHandlerReplacement(string oldHandlerType, Type newH } else { - var assemblies = AppDomain.CurrentDomain.GetAssemblies(); - var handlerType = assemblies.Select(x => x.GetType(oldHandlerType)).FirstOrDefault(x => x != null); - - views = handlerType is null - ? new List>() - : HandlerService - .Select(x => new KeyValuePair(x.ServiceType, GetRegisteredHandlerType(x))) - .Where(x => x.Value == handlerType) - .Select(x => new KeyValuePair(x.Key, x.Value!)) - .Distinct() - .ToList(); + // Match by name, like the replacement request itself. Looking the name up in the loaded + // assemblies can find a different Type when an assembly is loaded more than once. + views = HandlerService + .Select(x => new KeyValuePair(x.ServiceType, GetRegisteredHandlerType(x))) + .Where(x => x.Value?.FullName == oldHandlerType) + .Select(x => new KeyValuePair(x.Key, x.Value!)) + .Distinct() + .ToList(); if (views.Count > 0) replacedHandlers[oldHandlerType] = views.ToList(); diff --git a/src/Core/src/Platform/ElementExtensions.cs b/src/Core/src/Platform/ElementExtensions.cs index 6c7a873a8baa..07395d69bc2a 100644 --- a/src/Core/src/Platform/ElementExtensions.cs +++ b/src/Core/src/Platform/ElementExtensions.cs @@ -28,27 +28,6 @@ namespace Microsoft.Maui.Platform { public static partial class ElementExtensions { - static HashSet handlersWithConstructors = new HashSet(); - - static IElementHandler? CreateTypeWithInjection(this Type viewType, IMauiContext mauiContext) - { - var handlerType = mauiContext.Handlers.GetHandlerType(viewType); - - if (handlerType == null) - return null; - -#if ANDROID - if(mauiContext.Context != null) - { - return (IElementHandler)Extensions.DependencyInjection. - ActivatorUtilities.CreateInstance(mauiContext.Services, handlerType, mauiContext.Context); - } -#endif - - return (IElementHandler)Extensions.DependencyInjection. - ActivatorUtilities.CreateInstance(mauiContext.Services, handlerType); - } - public static IElementHandler ToHandler(this IElement view, IMauiContext context) { _ = view ?? throw new ArgumentNullException(nameof(view)); @@ -64,24 +43,9 @@ public static IElementHandler ToHandler(this IElement view, IMauiContext context handler = null; - // TODO Clean up this handler create. Handlers should probably create through the - // DI.Ext Service provider. We just register them all as transient? possibly? if (handler == null) { - var viewType = view.GetType(); - try - { - if (handlersWithConstructors.Contains(viewType)) - handler = viewType.CreateTypeWithInjection(context); - else - handler = context.Handlers.GetHandler(viewType, context); - } - catch (MissingMethodException) - { - handler = viewType.CreateTypeWithInjection(context); - if (handler != null) - handlersWithConstructors.Add(view.GetType()); - } + handler = context.Handlers.GetHandlerWithInjection(view.GetType(), context); } if (handler == null) diff --git a/src/Core/tests/DeviceTests/HandlerActivationTests.Android.cs b/src/Core/tests/DeviceTests/HandlerActivationTests.Android.cs new file mode 100644 index 000000000000..77799c91b4e7 --- /dev/null +++ b/src/Core/tests/DeviceTests/HandlerActivationTests.Android.cs @@ -0,0 +1,72 @@ +using Android.Content; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Maui.DeviceTests.Stubs; +using Microsoft.Maui.Handlers; +using Microsoft.Maui.Hosting; +using Microsoft.Maui.Platform; +using Xunit; + +namespace Microsoft.Maui.DeviceTests +{ + [Category(TestCategory.MauiContext)] + public class HandlerActivationTests + { + [Theory(DisplayName = "Injected Handler Captures The Current Android Context")] + [InlineData(false)] + [InlineData(true)] + public void InjectedHandlerCapturesCurrentAndroidContextAndDependency(bool singleton) + { + using var app = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => + { + handlers.AddHandler(); + if (singleton) + handlers.Add(ServiceDescriptor.Singleton(typeof(ContextElementStub), typeof(ContextCapturingHandler))); + }) + .Build(); + var firstAndroidContext = new ContextWrapper(MauiProgram.DefaultContext); + var secondAndroidContext = new ContextWrapper(MauiProgram.DefaultContext); + var firstContext = new MauiContext(app.Services, firstAndroidContext); + var secondContext = new MauiContext(app.Services, secondAndroidContext); + var firstDependency = new ContextDependency(); + var secondDependency = new ContextDependency(); + firstContext.AddSpecific(firstDependency); + secondContext.AddSpecific(secondDependency); + + var first = Assert.IsType(new ContextElementStub().ToHandler(firstContext)); + var again = Assert.IsType(new ContextElementStub().ToHandler(firstContext)); + var second = Assert.IsType(new ContextElementStub().ToHandler(secondContext)); + + Assert.NotSame(first, again); + Assert.Same(firstAndroidContext, first.AndroidContext); + Assert.Same(firstDependency, first.Dependency); + Assert.Same(firstAndroidContext, again.AndroidContext); + Assert.Same(secondAndroidContext, second.AndroidContext); + Assert.Same(secondDependency, second.Dependency); + } + + class ContextElementStub : ElementStub + { + } + + class ContextDependency + { + } + + class ContextCapturingHandler : ElementHandler + { + public ContextCapturingHandler(Context androidContext, ContextDependency dependency) + : base(ElementHandler.ElementMapper) + { + AndroidContext = androidContext; + Dependency = dependency; + } + + public Context AndroidContext { get; } + + public ContextDependency Dependency { get; } + + protected override object CreatePlatformElement() => new object(); + } + } +} diff --git a/src/Core/tests/UnitTests/Hosting/HostBuilderHandlerTests.cs b/src/Core/tests/UnitTests/Hosting/HostBuilderHandlerTests.cs index 0525564899cf..f8ddfe89d7e3 100644 --- a/src/Core/tests/UnitTests/Hosting/HostBuilderHandlerTests.cs +++ b/src/Core/tests/UnitTests/Hosting/HostBuilderHandlerTests.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.ExceptionServices; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Maui.Handlers; @@ -498,5 +499,302 @@ public ContextAwareService(IMauiContext mauiContext) public IMauiContext MauiContext { get; } } + + [Fact] + public void ToHandlerUsesActivatorUtilitiesForHandlerWithoutDefaultConstructor() + { + var dependency = new ConstructorDependency(); + var builder = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()); + builder.Services.AddSingleton(dependency); + using var mauiApp = builder.Build(); + var mauiContext = new MauiContext(mauiApp.Services); + + var handler = Assert.IsType(new ViewStub().ToHandler(mauiContext)); + + Assert.Same(dependency, handler.Dependency); + } + + [Fact] + public void ConstructorInjectionUsesCurrentContextAndHonorsFactoryOverrides() + { + using var app = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()) + .Build(); + var firstContext = new MauiContext(app.Services); + var secondContext = new MauiContext(app.Services); + var firstDependency = new ConstructorDependency(); + var secondDependency = new ConstructorDependency(); + firstContext.AddSpecific(firstDependency); + secondContext.AddSpecific(secondDependency); + + Assert.Same(firstDependency, Assert.IsType( + new ViewStub().ToHandler(firstContext)).Dependency); + Assert.Same(secondDependency, Assert.IsType( + new ViewStub().ToHandler(secondContext)).Dependency); + + var calls = 0; + firstContext.Handlers.GetCollection().AddHandler(_ => + { + calls++; + return new AlternateViewHandlerStub(); + }); + Assert.IsType(new ViewStub().ToHandler(firstContext)); + Assert.IsType(new ViewStub().ToHandler(secondContext)); + Assert.Equal(2, calls); + } + + [Fact] + public void ConstructorInjectionFailureIsNotRetried() + { + var calls = 0; + var builder = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()); + builder.Services.AddTransient(_ => + { + calls++; + throw new MissingMethodException("Dependency factory failed."); + }); + using var app = builder.Build(); + var context = new MauiContext(app.Services); + + Assert.Throws(() => new ViewStub().ToHandler(context)); + Assert.Equal(1, calls); + + context.AddSpecific(new ConstructorDependency()); + Assert.IsType(new ViewStub().ToHandler(context)); + } + + [Fact] + public void ToHandlerPrefersParameterlessConstructorWhenInjectionIsAlsoAvailable() + { + var builder = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()); + builder.Services.AddTransient(_ => + throw new InvalidOperationException("The parameterless constructor must not resolve dependencies.")); + using var app = builder.Build(); + var context = new MauiContext(app.Services); + + var handler = Assert.IsType(new ViewStub().ToHandler(context)); + + Assert.False(handler.UsedInjection); + } + + [Fact] + public void ToHandlerCreatesValueTypeHandlerWithoutReflectedParameterlessConstructor() + { + using var app = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()) + .Build(); + var context = new MauiContext(app.Services); + var view = Substitute.For(); + + var handler = Assert.IsType(view.ToHandler(context)); + + Assert.Same(context, handler.MauiContext); + Assert.Same(view, handler.VirtualView); + } + + [Fact] + public void ConstructorInjectionAvoidsMissingConstructorExceptions() + { + var builder = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()); + builder.Services.AddSingleton(new ConstructorDependency()); + using var app = builder.Build(); + var context = new MauiContext(app.Services); + var exceptions = 0; + var threadId = Environment.CurrentManagedThreadId; + EventHandler onException = (_, args) => + { + if (Environment.CurrentManagedThreadId == threadId && args.Exception is MissingMethodException) + exceptions++; + }; + + AppDomain.CurrentDomain.FirstChanceException += onException; + try + { + Assert.IsType(new ViewStub().ToHandler(context)); + Assert.Equal(0, exceptions); + Assert.IsType(new ViewStub().ToHandler(context)); + Assert.Equal(0, exceptions); + + context.Handlers.GetCollection().AddHandler(_ => new ButtonHandlerStub()); + Assert.IsType(new ViewStub().ToHandler(context)); + Assert.Equal(0, exceptions); + + MauiHotReloadHelper.ClearCache(Array.Empty()); + Assert.IsType(new ViewStub().ToHandler(context)); + Assert.Equal(0, exceptions); + } + finally + { + AppDomain.CurrentDomain.FirstChanceException -= onException; + MauiHotReloadHelper.Reset(); + } + + Assert.Throws(() => context.Handlers.GetHandler(typeof(ViewStub))); + } + + [Fact] + public void ConstructorInjectionDoesNotAffectOtherApps() + { + var builder = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()); + builder.Services.AddSingleton(new ConstructorDependency()); + using var firstApp = builder.Build(); + new ViewStub().ToHandler(new MauiContext(firstApp.Services)); + + using var secondApp = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler(_ => new AlternateViewHandlerStub())) + .Build(); + Assert.IsType(new ViewStub().ToHandler(new MauiContext(secondApp.Services))); + } + + [Fact] + public void HotReloadReplacesHandlerAfterConstructorInjection() + { + var builder = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()); + builder.Services.AddSingleton(new ConstructorDependency()); + using var app = builder.Build(); + var context = new MauiContext(app.Services); + MauiHotReloadHelper.RegisterHandlers(context.Handlers.GetCollection()); + try + { + Assert.IsType(new ViewStub().ToHandler(context)); + Assert.IsType(new ViewStub().ToHandler(context)); + + MauiHotReloadHelper.RegisterHandlerReplacement( + typeof(HandlerWithoutDefaultConstructorStub).FullName!, + typeof(AlternateViewHandlerStub)); + + Assert.IsType(new ViewStub().ToHandler(context)); + } + finally + { + MauiHotReloadHelper.Reset(); + } + } + + [Fact] + public void WrappedMissingConstructorFromInjectedDependencyIsNotRetried() + { + var calls = 0; + var exception = new HandlerNotFoundException("Wrapped.", new MissingMethodException()); + var builder = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => handlers.AddHandler()); + builder.Services.AddTransient(_ => + { + calls++; + throw exception; + }); + using var app = builder.Build(); + + Assert.Same(exception, Assert.Throws(() => + new ViewStub().ToHandler(new MauiContext(app.Services)))); + Assert.Equal(1, calls); + } + + [Fact] + public void SingletonRegistrationRequiringInjectionCreatesHandlerPerActivation() + { + using var app = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => + { + handlers.AddHandler(); + handlers.Add(ServiceDescriptor.Singleton(typeof(ViewStub), typeof(HandlerWithoutDefaultConstructorStub))); + }) + .Build(); + var firstContext = new MauiContext(app.Services); + var secondContext = new MauiContext(app.Services); + var firstDependency = new ConstructorDependency(); + var secondDependency = new ConstructorDependency(); + firstContext.AddSpecific(firstDependency); + secondContext.AddSpecific(secondDependency); + + var firstView = new ViewStub(); + var secondView = new ViewStub(); + var first = Assert.IsType(firstView.ToHandler(firstContext)); + var second = Assert.IsType(secondView.ToHandler(firstContext)); + var other = Assert.IsType(new ViewStub().ToHandler(secondContext)); + + Assert.NotSame(first, second); + Assert.Same(firstView, first.VirtualView); + Assert.Same(secondView, second.VirtualView); + Assert.Same(firstDependency, first.Dependency); + Assert.Same(firstDependency, second.Dependency); + Assert.Same(secondDependency, other.Dependency); + } + + [Fact] + public void CustomHandlersFactoryWrappedMissingConstructorFallsBackToInjection() + { + var handlers = Substitute.For(); + handlers.GetHandler(typeof(ViewStub)).Returns(_ => + throw new HandlerNotFoundException("Wrapped.", new MissingMethodException())); + handlers.GetHandlerType(typeof(ViewStub)).Returns(typeof(HandlerWithoutDefaultConstructorStub)); + var dependency = new ConstructorDependency(); + var builder = MauiApp.CreateBuilder(); + builder.Services.AddSingleton(handlers); + builder.Services.AddSingleton(dependency); + using var app = builder.Build(); + + var handler = Assert.IsType( + new ViewStub().ToHandler(new MauiContext(app.Services))); + + Assert.Same(dependency, handler.Dependency); + } + + [Fact] + public void CustomHandlersFactoryWrappedUnrelatedExceptionPropagates() + { + var handlers = Substitute.For(); + var exception = new HandlerNotFoundException("Wrapped.", new InvalidOperationException()); + handlers.GetHandler(typeof(ViewStub)).Returns(_ => throw exception); + var builder = MauiApp.CreateBuilder(); + builder.Services.AddSingleton(handlers); + using var app = builder.Build(); + + Assert.Same(exception, Assert.Throws(() => + new ViewStub().ToHandler(new MauiContext(app.Services)))); + handlers.DidNotReceive().GetHandlerType(Arg.Any()); + } + + class HandlerWithoutDefaultConstructorStub : ViewHandlerStub + { + public HandlerWithoutDefaultConstructorStub(ConstructorDependency dependency) + { + Dependency = dependency; + } + + public ConstructorDependency Dependency { get; } + } + + class ConstructorDependency { } + + class HandlerWithBothConstructors : ViewHandlerStub + { + public HandlerWithBothConstructors() { } + + public HandlerWithBothConstructors(ConstructorDependency dependency) + { + UsedInjection = true; + } + + public bool UsedInjection { get; } + } + + struct ValueTypeHandler : IElementHandler + { + public IMauiContext MauiContext { get; private set; } + public IElement VirtualView { get; private set; } + public object PlatformView => null; + public void SetMauiContext(IMauiContext context) => MauiContext = context; + public void SetVirtualView(IElement view) => VirtualView = view; + public void UpdateValue(string property) { } + public void Invoke(string command, object args = null) { } + public void DisconnectHandler() { } + } } -} \ No newline at end of file +}