diff --git a/src/SimpleInjector.Tests.Unit/RegisterConditionalTests.cs b/src/SimpleInjector.Tests.Unit/RegisterConditionalTests.cs index af3249b85..4744bda34 100644 --- a/src/SimpleInjector.Tests.Unit/RegisterConditionalTests.cs +++ b/src/SimpleInjector.Tests.Unit/RegisterConditionalTests.cs @@ -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 implementationTypeFactory = + c => { context = c; return typeof(NullLogger); }; + + container.RegisterConditional( + typeof(ILogger), + implementationTypeFactory, + Lifestyle.Singleton, + _ => true); + + // Act + container.GetInstance(); + + // Assert + Assert.IsNull(context.Consumer, message: $"Actual: {context.Consumer}"); + } + private static void RegisterConditionalConstant(Container container, T constant, Predicate predicate) { diff --git a/src/SimpleInjector/TypeFactoryContext.cs b/src/SimpleInjector/TypeFactoryContext.cs index 66c4a073a..920eb8878 100644 --- a/src/SimpleInjector/TypeFactoryContext.cs +++ b/src/SimpleInjector/TypeFactoryContext.cs @@ -39,10 +39,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; } /// Gets the closed generic service type that is to be created. @@ -54,7 +56,8 @@ internal TypeFactoryContext(Type serviceType, InjectionConsumerInfo consumer) /// service. This property will return null in case the service is resolved directly from the container. /// /// The or null. - 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.")]