From 581333c2a86450ea25b3432358b54fa3503489d2 Mon Sep 17 00:00:00 2001 From: Yohan Bainier Date: Wed, 10 May 2017 12:51:39 +0200 Subject: [PATCH] Introducing named-as-itself component registration --- Hypodermic.Tests/NamedTests.cpp | 15 +++++++++++++++ Hypodermic/Named.h | 27 +++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/Hypodermic.Tests/NamedTests.cpp b/Hypodermic.Tests/NamedTests.cpp index 3f23816..b17af5b 100644 --- a/Hypodermic.Tests/NamedTests.cpp +++ b/Hypodermic.Tests/NamedTests.cpp @@ -27,6 +27,21 @@ namespace Testing BOOST_CHECK(instance != nullptr); } + BOOST_AUTO_TEST_CASE(should_resolve_named_component_as_itself) + { + // Arrange + ContainerBuilder builder; + + // Act + builder.registerType< DefaultConstructible1 >().named("default1"); + + auto container = builder.build(); + + // Assert + auto instance = container->resolveNamed< DefaultConstructible1 >("default1"); + BOOST_CHECK(instance != nullptr); + } + BOOST_AUTO_TEST_CASE(should_not_resolve_named_component_without_its_name) { // Arrange diff --git a/Hypodermic/Named.h b/Hypodermic/Named.h index db84299..82e113d 100644 --- a/Hypodermic/Named.h +++ b/Hypodermic/Named.h @@ -37,12 +37,35 @@ namespace RegistrationDescriptorOperations }; public: - template + // This template avoids Early Template Instantiation issue + template typename TDelayedDescriptor::template UpdateDescriptor < - typename TDescriptorInfo::template RegisterBase< TBase >::Type + typename TDescriptorInfo::SelfRegistered::Type > ::Type& named(const std::string& name) + { + auto descriptor = static_cast< TDescriptor* >(this); + descriptor->addTypeIfMissing(createKeyForNamedType< InstanceType >(name)); + + auto updatedDescriptor = descriptor->template createUpdate< typename TDescriptorInfo::SelfRegistered::Type >(); + descriptor->registrationDescriptorUpdated()(updatedDescriptor); + + return *updatedDescriptor; + } + + // This template avoids Early Template Instantiation issue + template + typename std::enable_if + < + !std::is_same< TBase, InstanceType >::value, + typename TDelayedDescriptor::template UpdateDescriptor + < + typename TDescriptorInfo::template RegisterBase< TBase >::Type + > + ::Type& + > + ::type named(const std::string& name) { EnforceBaseOf< TBase, InstanceType >::act(); EnforceBaseNotAlreadyRegistered< TBase >::act();