Skip to content
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
19 changes: 17 additions & 2 deletions docs/design/HandlerResolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<TType>(Func<IServiceProvider, IElementHandler>)` when constructor arguments are required)
> remains the recommended approach.

## Types used in the resolution of Handlers to Views

### `MauiFactory`
Expand All @@ -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`
Expand Down
2 changes: 1 addition & 1 deletion src/Core/src/Hosting/Internal/MauiFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
86 changes: 85 additions & 1 deletion src/Core/src/Hosting/Internal/MauiHandlersFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
simonrozsival marked this conversation as resolved.
Resolved
&& activationServices?.ConstructorInjectionAttempted != true)
Comment thread
simonrozsival marked this conversation as resolved.
Resolved
Comment thread
simonrozsival marked this conversation as resolved.
Resolved
{
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);
Comment thread
simonrozsival marked this conversation as resolved.
Resolved
Comment thread
simonrozsival marked this conversation as resolved.
Resolved
Comment thread
simonrozsival marked this conversation as resolved.
Resolved

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);
Comment thread
simonrozsival marked this conversation as resolved.
Resolved
}
#endif

return (IElementHandler)ActivatorUtilities.CreateInstance(mauiContext.Services, handlerType);
}

IElementHandler? GetHandler(Type type, IServiceProvider implementationFactoryServiceProvider)
{
if (TryGetVirtualViewHandlerServiceType(type) is Type serviceType
Expand Down Expand Up @@ -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))
Expand All @@ -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)
Expand Down
19 changes: 8 additions & 11 deletions src/Core/src/HotReload/HotReloadHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<KeyValuePair<Type, Type>>()
: HandlerService
.Select(x => new KeyValuePair<Type, Type?>(x.ServiceType, GetRegisteredHandlerType(x)))
.Where(x => x.Value == handlerType)
.Select(x => new KeyValuePair<Type, Type>(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<Type, Type?>(x.ServiceType, GetRegisteredHandlerType(x)))
.Where(x => x.Value?.FullName == oldHandlerType)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[moderate] Regression Prevention and Test Coverage - The replacement-matching change has no discriminating negative test for an unrelated registered handler. HotReloadReplacesHandlerAfterConstructorInjection registers only the handler being replaced, and the existing pending-replacement tests likewise register only their target. Broadening this predicate to accept every non-null registered handler type would therefore satisfy their assertions while replacing unrelated controls' handlers in an app with multiple registrations. Register and activate a second handler with a different FullName, replace the first, and assert that the second registration and subsequent activation remain unchanged.

.Select(x => new KeyValuePair<Type, Type>(x.Key, x.Value!))
.Distinct()
.ToList();

if (views.Count > 0)
replacedHandlers[oldHandlerType] = views.ToList();
Expand Down
38 changes: 1 addition & 37 deletions src/Core/src/Platform/ElementExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,6 @@ namespace Microsoft.Maui.Platform
{
public static partial class ElementExtensions
{
static HashSet<Type> handlersWithConstructors = new HashSet<Type>();

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));
Expand All @@ -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)
Expand Down
72 changes: 72 additions & 0 deletions src/Core/tests/DeviceTests/HandlerActivationTests.Android.cs
Original file line number Diff line number Diff line change
@@ -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<ContextElementStub, ContextCapturingHandler>();
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<ContextCapturingHandler>(new ContextElementStub().ToHandler(firstContext));
var again = Assert.IsType<ContextCapturingHandler>(new ContextElementStub().ToHandler(firstContext));
var second = Assert.IsType<ContextCapturingHandler>(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<ContextElementStub, object>
{
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();
}
}
}
Loading
Loading