Skip to content

Commit

Permalink
Fixes the issue where lifetime cannot be overridden after using the D…
Browse files Browse the repository at this point in the history
…efaultLifetime call
  • Loading branch information
NikolayPianikov committed Dec 21, 2023
1 parent bfa2316 commit 95ccde9
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/Pure.DI.Core/Core/SetupsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down
41 changes: 41 additions & 0 deletions tests/Pure.DI.IntegrationTests/LifetimesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IService>().As(Lifetime.Transient).To<Service>()
.Root<IService>("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()
{
Expand Down

0 comments on commit 95ccde9

Please sign in to comment.