diff --git a/src/SteroidsDI.Tests/Cases/FactoryTests.cs b/src/SteroidsDI.Tests/Cases/FactoryTests.cs index 6b043f8..44e2be3 100644 --- a/src/SteroidsDI.Tests/Cases/FactoryTests.cs +++ b/src/SteroidsDI.Tests/Cases/FactoryTests.cs @@ -21,6 +21,49 @@ public void Named_Binding_Should_Throw_On_Unknown_Lifetime() Use the 'Named'/'Default' overloads with explicit Lifetime or first register 'SteroidsDI.Tests.IBuilder' in the DI container."); } + [Test] + public void Named_Binding_Should_Allow_The_Same_Type_With_Different_Names() + { + var services = new ServiceCollection() + .AddTransient() + .For() + .Named("aaa") + .Named("bbb") + .Named("ccc") + .Services; + services.Count.ShouldBe(5); + } + + [Test] + public void Default_Binding_Should_Allow_Redeclaration() + { + var services = new ServiceCollection() + .AddTransient() + .For() + .Default() + .Default() + .Services; + services.Count.ShouldBe(3); + var def = (NamedBinding)services.Last().ImplementationInstance!; + def.Name.ShouldBeNull(); + def.ImplementationType.ShouldBe(typeof(SpecialBuilder)); + } + + [Test] + public void Default_Binding_Should_Allow_Replace() + { + var services = new ServiceCollection() + .AddTransient() + .For() + .Default() + .Default() + .Services; + services.Count.ShouldBe(4); + var def = (NamedBinding)services[2].ImplementationInstance!; + def.Name.ShouldBeNull(); + def.ImplementationType.ShouldBe(typeof(SpecialBuilderOver9000Level)); + } + [Test] [TestCase(true)] [TestCase(false)] diff --git a/src/SteroidsDI/Factory/BindingContext.cs b/src/SteroidsDI/Factory/BindingContext.cs index 0973273..2251c10 100644 --- a/src/SteroidsDI/Factory/BindingContext.cs +++ b/src/SteroidsDI/Factory/BindingContext.cs @@ -90,7 +90,18 @@ public BindingContext Default(ServiceLifetime lifetim if (existing == null) Services.Add(new ServiceDescriptor(typeof(TImplementation), typeof(TImplementation), lifetime)); - Services.AddSingleton(new NamedBinding(null, typeof(TService), typeof(TImplementation))); + var def = new NamedBinding(null, typeof(TService), typeof(TImplementation)); + var descriptor = ServiceDescriptor.Singleton(def); + for (int i = 0; i < Services.Count; ++i) + { + if (Services[i].ImplementationInstance is NamedBinding named && named.Name is null && named.ServiceType == typeof(TService)) + { + Services[i] = descriptor; + return this; + } + } + + Services.Add(descriptor); return this; } diff --git a/src/SteroidsDI/Factory/NamedBinding.cs b/src/SteroidsDI/Factory/NamedBinding.cs index 6db6a44..665032f 100644 --- a/src/SteroidsDI/Factory/NamedBinding.cs +++ b/src/SteroidsDI/Factory/NamedBinding.cs @@ -7,7 +7,7 @@ namespace SteroidsDI; /// type in the required context. /// [DebuggerDisplay("{Name}: {ServiceType.Name} -> {ImplementationType.Name}")] -internal sealed class NamedBinding +internal sealed record NamedBinding { public NamedBinding(object? name, Type serviceType, Type implementationType) {