Skip to content

Commit

Permalink
TypeFactoryContext got accidental non-null consumer for root registra…
Browse files Browse the repository at this point in the history
…tions, which was introduced in change #698. Fixes #734.

(cherry picked from commit bb26728)
  • Loading branch information
dotnetjunkie committed Jul 23, 2019
1 parent 7ee8721 commit bd5f92c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
25 changes: 25 additions & 0 deletions src/SimpleInjector.Tests.Unit/RegisterConditionalTests.cs
Expand Up @@ -1727,6 +1727,31 @@ public void GetInstance_ConditionalRegistrationAsRootType_PredicateContextConsum
"When requesint a root type, the Consumer property should be null.");
}

// Regression in v4.5.2. See #734
[TestMethod]
public void GetInstance_ResolvingConditionalRootObject_SuppliesImplementationTypeFactoryWithNullConsumer()
{
// Arrange
var container = new Container();

TypeFactoryContext context = null;

Func<TypeFactoryContext, Type> implementationTypeFactory =
c => { context = c; return typeof(NullLogger); };

container.RegisterConditional(
typeof(ILogger),
implementationTypeFactory,
Lifestyle.Singleton,
_ => true);

// Act
container.GetInstance<ILogger>();

// Assert
Assert.IsNull(context.Consumer, message: $"Actual: {context.Consumer}");
}

private static void RegisterConditionalConstant<T>(Container container, T constant,
Predicate<PredicateContext> predicate)
{
Expand Down
7 changes: 5 additions & 2 deletions src/SimpleInjector/TypeFactoryContext.cs
Expand Up @@ -20,10 +20,12 @@ namespace SimpleInjector
[DebuggerDisplay(nameof(TypeFactoryContext) + " ({" + nameof(TypeFactoryContext.DebuggerDisplay) + ", nq})")]
public sealed class TypeFactoryContext : ApiObject
{
private readonly InjectionConsumerInfo consumer;

internal TypeFactoryContext(Type serviceType, InjectionConsumerInfo consumer)
{
this.ServiceType = serviceType;
this.Consumer = consumer;
this.consumer = consumer;
}

/// <summary>Gets the closed generic service type that is to be created.</summary>
Expand All @@ -35,7 +37,8 @@ internal TypeFactoryContext(Type serviceType, InjectionConsumerInfo consumer)
/// service. This property will return null in case the service is resolved directly from the container.
/// </summary>
/// <value>The <see cref="InjectionConsumerInfo"/> or null.</value>
public InjectionConsumerInfo Consumer { get; }
public InjectionConsumerInfo Consumer =>
this.consumer != InjectionConsumerInfo.Root ? this.consumer : null;

[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode",
Justification = "This method is called by the debugger.")]
Expand Down

0 comments on commit bd5f92c

Please sign in to comment.