Skip to content

Commit

Permalink
ObjectFactory should verify against a null serviceProvider (#82739)
Browse files Browse the repository at this point in the history
  • Loading branch information
pedrobsaila committed Mar 15, 2023
1 parent aeed019 commit 32ebb66
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ private static MethodInfo GetMethodInfo<T>(Expression<T> expr)
return service;
}

private static NewExpression BuildFactoryExpression(
private static BlockExpression BuildFactoryExpression(
ConstructorInfo constructor,
int?[] parameterMap,
Expression serviceProvider,
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
using static Microsoft.Extensions.DependencyInjection.Tests.AsyncServiceScopeTests;

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

[Fact]
public void FactoryActivatorThrowsOnNullProvider()
{
var f = ActivatorUtilities.CreateFactory(typeof(ClassWithA), new Type[0]);
Assert.Throws<ArgumentNullException>(() => f(serviceProvider: null, null));
}

[Fact]
public void CreateInstance_ClassWithABCS_UsesTheLongestAvailableConstructor_ParameterOrderDoesntMatter()
{
Expand Down

0 comments on commit 32ebb66

Please sign in to comment.