Skip to content

Commit 32ebb66

Browse files
authored
ObjectFactory should verify against a null serviceProvider (#82739)
1 parent aeed019 commit 32ebb66

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ private static MethodInfo GetMethodInfo<T>(Expression<T> expr)
242242
return service;
243243
}
244244

245-
private static NewExpression BuildFactoryExpression(
245+
private static BlockExpression BuildFactoryExpression(
246246
ConstructorInfo constructor,
247247
int?[] parameterMap,
248248
Expression serviceProvider,
@@ -281,7 +281,8 @@ private static NewExpression BuildFactoryExpression(
281281
constructorArguments[i] = Expression.Convert(constructorArguments[i], parameterType);
282282
}
283283

284-
return Expression.New(constructor, constructorArguments);
284+
return Expression.Block(Expression.IfThen(Expression.Equal(serviceProvider, Expression.Constant(null)), Expression.Throw(Expression.Constant(new ArgumentNullException(nameof(serviceProvider))))),
285+
Expression.New(constructor, constructorArguments));
285286
}
286287

287288
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP

src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ActivatorUtilitiesTests.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
using System;
55
using Microsoft.DotNet.RemoteExecutor;
66
using Xunit;
7-
using static Microsoft.Extensions.DependencyInjection.Tests.AsyncServiceScopeTests;
87

98
namespace Microsoft.Extensions.DependencyInjection.Tests
109
{
@@ -91,6 +90,13 @@ public void TypeActivatorThrowsOnNullProvider()
9190
Assert.Throws<ArgumentNullException>(() => ActivatorUtilities.CreateInstance<ClassWithABCS>(null, "hello"));
9291
}
9392

93+
[Fact]
94+
public void FactoryActivatorThrowsOnNullProvider()
95+
{
96+
var f = ActivatorUtilities.CreateFactory(typeof(ClassWithA), new Type[0]);
97+
Assert.Throws<ArgumentNullException>(() => f(serviceProvider: null, null));
98+
}
99+
94100
[Fact]
95101
public void CreateInstance_ClassWithABCS_UsesTheLongestAvailableConstructor_ParameterOrderDoesntMatter()
96102
{

0 commit comments

Comments
 (0)