From 551670052314867b7db66ad69946567914c6fb57 Mon Sep 17 00:00:00 2001 From: Ichthyostega Date: Sun, 18 Mar 2018 02:11:46 +0100 Subject: [PATCH] DI: draft configuration for using a service implementation created elsewhere --- research/try.cpp | 80 +++++++++++++++++++++++++++++++++++++++- wiki/thinkPad.ichthyo.mm | 21 ++++++++--- 2 files changed, 93 insertions(+), 8 deletions(-) diff --git a/research/try.cpp b/research/try.cpp index 04483dc2c..2d46eb391 100644 --- a/research/try.cpp +++ b/research/try.cpp @@ -200,6 +200,24 @@ class DependInject Depend::factory = Depend::disabledFactory; } + static void + activateServiceAccess (SRV& newInstance) + { + ClassLock guard; + if (Depend::instance) + throw error::Logic("Attempt to activate an external service implementation, " + "but another instance has already been dependency-injected." + , error::LUMIERA_ERROR_LIFECYCLE); + Depend::instance = &newInstance; + } + + static void + deactivateServiceAccess() + { + ClassLock guard; + Depend::instance = nullptr; + } + template @@ -214,13 +232,42 @@ class DependInject }); } + template class ServiceInstance { + std::unique_ptr instance_; + public: ServiceInstance() + : instance_(new IMP{}) { - + activateServiceAccess (*instance_); + } + + ~ServiceInstance() + { + deactivateServiceAccess(); + } + + explicit + operator bool() const + { + return bool(instance_); + } + + IMP& + operator* () const + { + ENSURE (instance_); + return *instance_; + } + + IMP* + operator-> () const + { + ENSURE (instance_); + return instance_.get(); } }; @@ -256,7 +303,7 @@ struct Dummy ~Dummy() { checksum -= N; cout << "~Dummy<"<"<{}().probe() ); SHOW_EXPR( checksum ); + struct SubDummy + : Dummy<3> + { + virtual int + probe() override + { + return -checksum + offset; + } + + int offset = 0; + }; + + Depend> dep3; + SHOW_EXPR( checksum ); + { + DependInject>::ServiceInstance service{}; + CHECK (service); + SHOW_EXPR( checksum ); + SHOW_EXPR( dep3().probe() ); + SHOW_EXPR( checksum ); + service->offset = 5; + SHOW_EXPR( dep3().probe() ); + SHOW_EXPR( checksum ); + } + SHOW_EXPR( checksum ); + SHOW_EXPR( dep3().probe() ); + VERIFY_ERROR (LIFECYCLE, DependInject::ServiceInstance{} ); + SHOW_EXPR( checksum ); + cout << "\n.gulp.\n"; diff --git a/wiki/thinkPad.ichthyo.mm b/wiki/thinkPad.ichthyo.mm index a0bf63ce4..535ca26d5 100644 --- a/wiki/thinkPad.ichthyo.mm +++ b/wiki/thinkPad.ichthyo.mm @@ -26807,8 +26807,10 @@ - - + + + + @@ -26823,9 +26825,14 @@ + + + + + + + - - @@ -27006,7 +27013,7 @@ - + @@ -27018,8 +27025,10 @@ + - + +