diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs index 2ebcf0819b776..21b4646713bae 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs @@ -242,7 +242,7 @@ private static MethodInfo GetMethodInfo(Expression expr) return service; } - private static NewExpression BuildFactoryExpression( + private static BlockExpression BuildFactoryExpression( ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, @@ -281,7 +281,8 @@ private static NewExpression BuildFactoryExpression( constructorArguments[i] = Expression.Convert(constructorArguments[i], parameterType); } - return Expression.New(constructor, constructorArguments); + return Expression.Block(Expression.IfThen(Expression.Equal(serviceProvider, Expression.Constant(null)), Expression.Throw(Expression.Constant(new ArgumentNullException(nameof(serviceProvider))))), + Expression.New(constructor, constructorArguments)); } #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ActivatorUtilitiesTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ActivatorUtilitiesTests.cs index f867f014906ee..c143e90a94301 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ActivatorUtilitiesTests.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ActivatorUtilitiesTests.cs @@ -4,7 +4,6 @@ using System; using Microsoft.DotNet.RemoteExecutor; using Xunit; -using static Microsoft.Extensions.DependencyInjection.Tests.AsyncServiceScopeTests; namespace Microsoft.Extensions.DependencyInjection.Tests { @@ -91,6 +90,13 @@ public void TypeActivatorThrowsOnNullProvider() Assert.Throws(() => ActivatorUtilities.CreateInstance(null, "hello")); } + [Fact] + public void FactoryActivatorThrowsOnNullProvider() + { + var f = ActivatorUtilities.CreateFactory(typeof(ClassWithA), new Type[0]); + Assert.Throws(() => f(serviceProvider: null, null)); + } + [Fact] public void CreateInstance_ClassWithABCS_UsesTheLongestAvailableConstructor_ParameterOrderDoesntMatter() {