From 95ccde91bb1d0e9185cfbac6fb03ef635272767f Mon Sep 17 00:00:00 2001 From: Nikolay Pianikov Date: Thu, 21 Dec 2023 13:47:34 +0300 Subject: [PATCH] Fixes the issue where lifetime cannot be overridden after using the DefaultLifetime call --- src/Pure.DI.Core/Core/SetupsBuilder.cs | 18 +++++--- .../LifetimesTests.cs | 41 +++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/src/Pure.DI.Core/Core/SetupsBuilder.cs b/src/Pure.DI.Core/Core/SetupsBuilder.cs index 3eeaa796..61cbfdf7 100644 --- a/src/Pure.DI.Core/Core/SetupsBuilder.cs +++ b/src/Pure.DI.Core/Core/SetupsBuilder.cs @@ -31,13 +31,19 @@ private MdBinding Binding { get { - _binding ??= new MdBinding(); + if (_binding is { } binding) + { + return binding; + } + + var newBinding = new MdBinding(); if (_defaultLifetime.HasValue) { - _binding = _binding.Value with { Lifetime = _defaultLifetime.Value.Lifetime }; + newBinding = newBinding with { Lifetime = _defaultLifetime.Value.Lifetime }; } - return _binding.Value; + _binding = newBinding; + return newBinding; } set => _binding = value; @@ -130,9 +136,11 @@ public void VisitTagAttribute(in MdTagAttribute tagAttribute) => public void VisitOrdinalAttribute(in MdOrdinalAttribute ordinalAttribute) => _ordinalAttributes.Add(ordinalAttribute); - public void VisitLifetime(in MdLifetime lifetime) => + public void VisitLifetime(in MdLifetime lifetime) + { Binding = Binding with { Lifetime = lifetime }; - + } + public void VisitTag(in MdTag tag) => _tags.Add(tag); public void VisitFinish() => FinishSetup(); diff --git a/tests/Pure.DI.IntegrationTests/LifetimesTests.cs b/tests/Pure.DI.IntegrationTests/LifetimesTests.cs index 83bfee2c..14e35a66 100644 --- a/tests/Pure.DI.IntegrationTests/LifetimesTests.cs +++ b/tests/Pure.DI.IntegrationTests/LifetimesTests.cs @@ -43,6 +43,47 @@ public static void Main() result.StdOut.ShouldBe(ImmutableArray.Create("True"), result); } + [Fact] + public async Task ShouldSupportTransientWhenDefaultLifetimeWasDefined() + { + // Given + + // When + var result = await """ + using System; + using Pure.DI; + + namespace Sample + { + interface IService {} + class Service: IService {} + static class Setup + { + private static void SetupComposition() + { + DI.Setup("Composition") + .DefaultLifetime(Lifetime.Singleton) + .Bind().As(Lifetime.Transient).To() + .Root("Service"); + } + } + + public class Program + { + public static void Main() + { + var composition = new Composition(); + Console.WriteLine(composition.Service != composition.Service); + } + } + } + """.RunAsync(); + + // Then + result.Success.ShouldBeTrue(result); + result.StdOut.ShouldBe(ImmutableArray.Create("True"), result); + } + [Fact] public async Task ShouldAssumeTransientWhenNotSpecified() {