Skip to content

Don't use System.Linq.Expressions in ActivatorUtilities.CreateFactory with AOT #81258

@JamesNK

Description

@JamesNK

ActivatorUtilities.CreateFactory uses compiled expressions to generate a high-performance factory on CoreCLR:

public static ObjectFactory CreateFactory(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType,
Type[] argumentTypes)
{
CreateFactoryInternal(instanceType, argumentTypes, out ParameterExpression provider, out ParameterExpression argumentArray, out Expression factoryExpressionBody);
var factoryLambda = Expression.Lambda<Func<IServiceProvider, object?[]?, object>>(
factoryExpressionBody, provider, argumentArray);
Func<IServiceProvider, object?[]?, object>? result = factoryLambda.Compile();
return result.Invoke;
}

NativeAOT doesn't support compiled expressions. Expressions is now a negative:

  • Expressions are interpreted, reducing performance compared to standard .NET reflection.
  • System.Linq.Expressions usage increases app size

CreateFactory should check for RuntimeFeature.IsDynamicCodeSupported and provide a delegate that uses standard .NET reflection when dynamic code isn't supported.

For example:

https://github.com/dotnet/aspnetcore/blob/4d75ee9a7fbad112e29b8a1d77c7d96965f62b40/src/Shared/PropertyHelper/PropertyHelper.cs#L215-L243

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions