├── .gitmodules ├── examples ├── example_service_locator │ ├── makefile │ └── main.cpp └── example_dependancy_injection │ ├── makefile │ └── main.cpp ├── tests ├── makefile └── ServiceLocatorTests.cpp ├── README.md ├── LICENSE └── ServiceLocator.hpp /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tests/Catch"] 2 | path = tests/Catch 3 | url = https://github.com/philsquared/Catch.git 4 | -------------------------------------------------------------------------------- /examples/example_service_locator/makefile: -------------------------------------------------------------------------------- 1 | example: main.cpp 2 | $(CXX) -std=c++11 -o example main.cpp -I../../ 3 | 4 | -------------------------------------------------------------------------------- /examples/example_dependancy_injection/makefile: -------------------------------------------------------------------------------- 1 | example: main.cpp 2 | $(CXX) -std=c++11 -o example main.cpp -I../../ 3 | 4 | -------------------------------------------------------------------------------- /tests/makefile: -------------------------------------------------------------------------------- 1 | tests: ServiceLocatorTests.cpp 2 | $(CXX) -std=c++11 -o tests ServiceLocatorTests.cpp -I../ -ICatch/include 3 | 4 | -------------------------------------------------------------------------------- /examples/example_service_locator/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "ServiceLocator.hpp" 3 | 4 | template 5 | using sptr = std::shared_ptr; 6 | 7 | class IFood { 8 | public: 9 | virtual std::string name() = 0; 10 | }; 11 | 12 | class Banana : public IFood { 13 | public: 14 | std::string name() override { 15 | return "Banana"; 16 | } 17 | }; 18 | 19 | class Pizza : public IFood { 20 | public: 21 | std::string name() override { 22 | return "Pizza"; 23 | } 24 | }; 25 | 26 | class IAnimal { 27 | public: 28 | virtual void eatFavouriteFood() = 0; 29 | }; 30 | 31 | class Monkey : public IAnimal { 32 | private: 33 | sptr _food; 34 | 35 | public: 36 | Monkey(SLContext_sptr slc) : _food(slc->resolve("Monkey")) { 37 | } 38 | 39 | void eatFavouriteFood() override { 40 | std::cout << "Monkey eats " << _food->name() << "\n"; 41 | } 42 | }; 43 | 44 | class Human : public IAnimal { 45 | private: 46 | sptr _food; 47 | 48 | public: 49 | Human(SLContext_sptr slc) : _food(slc->resolve("Human")) { 50 | } 51 | 52 | void eatFavouriteFood() override { 53 | std::cout << "Human eats " << _food->name() << "\n"; 54 | } 55 | }; 56 | 57 | int main(int argc, const char * argv[]) { 58 | auto sl = ServiceLocator::create(); 59 | sl->bind("Monkey").to([] (SLContext_sptr slc) { return new Monkey(slc); }); 60 | sl->bind("Human").to([] (SLContext_sptr slc) { return new Human(slc); }); 61 | sl->bind("Monkey").toNoDependancy(); 62 | sl->bind("Human").toNoDependancy(); 63 | 64 | auto slc = sl->getContext(); 65 | 66 | auto monkey = slc->resolve("Monkey"); 67 | monkey->eatFavouriteFood(); 68 | 69 | auto human = slc->resolve("Human"); 70 | human->eatFavouriteFood(); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /examples/example_dependancy_injection/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "ServiceLocator.hpp" 4 | 5 | template 6 | using sptr = std::shared_ptr; 7 | 8 | // Some plain interfaces 9 | class IFood { 10 | public: 11 | virtual std::string name() = 0; 12 | }; 13 | 14 | class IAnimal { 15 | public: 16 | virtual void eatFavouriteFood() = 0; 17 | }; 18 | 19 | 20 | // Concrete classes which implement our interfaces, these 2 have no dependancies 21 | class Banana : public IFood { 22 | public: 23 | std::string name() override { 24 | return "Banana"; 25 | } 26 | }; 27 | 28 | class Pizza : public IFood { 29 | public: 30 | std::string name() override { 31 | return "Pizza"; 32 | } 33 | }; 34 | 35 | // Monkey requires a favourite food, note it is not dependant on ServiceLocator now 36 | class Monkey : public IAnimal { 37 | private: 38 | sptr _food; 39 | 40 | public: 41 | Monkey(sptr food) : _food(food) { 42 | } 43 | 44 | void eatFavouriteFood() override { 45 | std::cout << "Monkey eats " << _food->name() << "\n"; 46 | } 47 | }; 48 | 49 | // Human requires a favourite food, note it is not dependant on ServiceLocator now 50 | class Human : public IAnimal { 51 | private: 52 | sptr _food; 53 | 54 | public: 55 | Human(sptr food) : _food(food) { 56 | } 57 | 58 | void eatFavouriteFood() override { 59 | std::cout << "Human eats " << _food->name() << "\n"; 60 | } 61 | }; 62 | 63 | /* The SLModule classes are ServiceLocator aware, and they are also intimate with the concrete classes they bind to 64 | and so know what dependancies are required to create instances */ 65 | class FoodSLModule : public ServiceLocator::Module { 66 | public: 67 | void load() override { 68 | bind("Monkey").to([] (SLContext_sptr slc) { 69 | return new Banana(); 70 | }); 71 | bind("Human").to([] (SLContext_sptr slc) { 72 | return new Pizza(); 73 | }); 74 | } 75 | }; 76 | 77 | class AnimalsSLModule : public ServiceLocator::Module { 78 | public: 79 | void load() override { 80 | bind("Human").to([] (SLContext_sptr slc) { 81 | return new Human(slc->resolve("Human")); 82 | }); 83 | bind("Monkey").to([] (SLContext_sptr slc) { 84 | return new Monkey(slc->resolve("Monkey")); 85 | }); 86 | } 87 | }; 88 | 89 | int main(int argc, const char * argv[]) { 90 | auto sl = ServiceLocator::create(); 91 | 92 | sl->modules() 93 | .add() 94 | .add(); 95 | 96 | auto slc = sl->getContext(); 97 | 98 | std::vector> animals; 99 | slc->resolveAll(&animals); 100 | 101 | for(auto animal : animals) { 102 | animal->eatFavouriteFood(); 103 | } 104 | 105 | return 0; 106 | } 107 | -------------------------------------------------------------------------------- /tests/ServiceLocatorTests.cpp: -------------------------------------------------------------------------------- 1 | #define CATCH_CONFIG_MAIN 2 | #include 3 | 4 | #include 5 | #include "ServiceLocator.hpp" 6 | 7 | class ITest { 8 | public: 9 | std::string contextPath; 10 | ITest(SLContext_sptr slc) { 11 | auto slcp = slc.get(); 12 | while(slcp->getParent() != nullptr) { 13 | contextPath = contextPath + slcp->getInterfaceTypeName() + "->"; 14 | slcp = slcp->getParent(); 15 | } 16 | } 17 | 18 | virtual std::string getIt() = 0; 19 | }; 20 | 21 | class TransientDestructor { 22 | public: 23 | TransientDestructor(SLContext_sptr slc) { 24 | } 25 | 26 | int* destructCount; 27 | 28 | virtual ~TransientDestructor() { 29 | (*destructCount)++; 30 | } 31 | }; 32 | 33 | class TestA : public ITest { 34 | public: 35 | TestA(SLContext_sptr slc) : ITest(slc) { 36 | } 37 | 38 | virtual std::string getIt() override { 39 | return "TestA"; 40 | } 41 | }; 42 | 43 | class TestB : public ITest { 44 | public: 45 | TestB(SLContext_sptr slc) : ITest(slc) { 46 | } 47 | 48 | virtual std::string getIt() override { 49 | return "TestB"; 50 | } 51 | }; 52 | 53 | class TestC { 54 | public: 55 | std::shared_ptr test; 56 | 57 | TestC(SLContext_sptr slc) { 58 | test = slc->tryResolve(); 59 | } 60 | 61 | std::string getIt() { 62 | return "TestC"; 63 | } 64 | }; 65 | 66 | class TestNoSL { 67 | public: 68 | TestNoSL() { 69 | } 70 | 71 | std::string getIt() { 72 | return "TestNoSL"; 73 | } 74 | }; 75 | 76 | static int TestEagerCount = 0; 77 | class TestEager { 78 | public: 79 | TestEager() { 80 | TestEagerCount++; 81 | } 82 | }; 83 | 84 | 85 | class TestAModule : public ServiceLocator::Module { 86 | public: 87 | void load() override { 88 | bind().to().asSingleton(); 89 | } 90 | }; 91 | 92 | class TestCModule : public ServiceLocator::Module { 93 | public: 94 | void load() override { 95 | bind().toSelf(); 96 | } 97 | }; 98 | 99 | 100 | TEST_CASE( "ServiceLocator", "[servicelocator]" ) { 101 | GIVEN("a ServiceLocator") { 102 | auto sl = ServiceLocator::create(); 103 | 104 | SECTION("Basic type binding") { 105 | sl->bind().to(); 106 | auto slc = sl->getContext(); 107 | 108 | auto a = slc->resolve(); 109 | 110 | REQUIRE(a->getIt() == "TestA"); 111 | REQUIRE(a->contextPath == "ITest->"); 112 | } 113 | 114 | SECTION("Transient Destructor") { 115 | sl->bind().toSelf(); 116 | auto slc = sl->getContext(); 117 | 118 | int destructCount = 0; 119 | { 120 | auto a = slc->resolve(); 121 | 122 | a->destructCount = &destructCount; 123 | } 124 | // a is out of scope and SL should not have a shared_ptr to the instance so it should destruct 125 | 126 | REQUIRE(destructCount == 1); 127 | } 128 | 129 | SECTION("Singleton no Destructor") { 130 | sl->bind().toSelf().asSingleton(); 131 | auto slc = sl->getContext(); 132 | 133 | int destructCount = 0; 134 | { 135 | auto a = slc->resolve(); 136 | 137 | a->destructCount = &destructCount; 138 | } 139 | // a is out of scope and SL should have a shared_ptr to the instance so it should not destruct 140 | 141 | REQUIRE(destructCount == 0); 142 | } 143 | 144 | SECTION("Basic type binding as Singleton") { 145 | sl->bind().to().asSingleton(); 146 | auto slc = sl->getContext(); 147 | 148 | auto a = slc->resolve(); 149 | auto aa = slc->resolve(); 150 | 151 | REQUIRE(a == aa); 152 | REQUIRE(a->contextPath == "ITest->"); 153 | } 154 | 155 | SECTION("Basic type binding to Instance") { 156 | auto sa = std::shared_ptr(new TestNoSL()); 157 | sl->bind().toInstance(sa); 158 | auto slc = sl->getContext(); 159 | 160 | auto a = slc->resolve(); 161 | auto aa = slc->resolve(); 162 | 163 | REQUIRE(a == aa); 164 | REQUIRE(a == sa); 165 | } 166 | 167 | SECTION("Basic type binding as transient") { 168 | sl->bind().to(); 169 | auto slc = sl->getContext(); 170 | 171 | auto a1 = slc->resolve(); 172 | auto a2 = slc->resolve(); 173 | 174 | REQUIRE(a1 != a2); 175 | } 176 | 177 | SECTION("Binding to implementation, tryResolve to null") { 178 | sl->bind().toSelf(); 179 | auto slc = sl->getContext(); 180 | 181 | auto c = slc->resolve(); 182 | 183 | REQUIRE(c->getIt() == "TestC"); 184 | REQUIRE(c->test == nullptr); 185 | } 186 | 187 | SECTION("Deep binding") { 188 | sl->bind().to(); 189 | sl->bind().toSelf(); 190 | auto slc = sl->getContext(); 191 | 192 | auto c = slc->resolve(); 193 | 194 | REQUIRE(c->getIt() == "TestC"); 195 | REQUIRE(c->test != nullptr); 196 | REQUIRE(c->test->getIt() == "TestA"); 197 | REQUIRE(c->test->contextPath == "ITest->TestC->"); 198 | } 199 | 200 | SECTION("Binding to implementation") { 201 | sl->bind().to(); 202 | sl->bind().toSelf(); 203 | auto slc = sl->getContext(); 204 | 205 | auto c = slc->resolve(); 206 | 207 | REQUIRE(c->getIt() == "TestC"); 208 | REQUIRE(c->test->getIt() == "TestA"); 209 | } 210 | 211 | SECTION("Duplicate binding throws") { 212 | sl->bind().to(); 213 | 214 | REQUIRE_THROWS((sl->bind().to())); 215 | } 216 | 217 | SECTION("Named binding") { 218 | sl->bind("X").to(); 219 | sl->bind("Y").to(); 220 | auto slc = sl->getContext(); 221 | 222 | std::shared_ptr x; 223 | REQUIRE_THROWS([&] () { 224 | x = slc->resolve(); 225 | }()); 226 | 227 | x = slc->resolve("X"); 228 | auto y = slc->resolve("Y"); 229 | 230 | REQUIRE(x != y); 231 | REQUIRE(x->getIt() == "TestA"); 232 | REQUIRE(y->getIt() == "TestB"); 233 | } 234 | 235 | SECTION("Binding to transient function") { 236 | sl->bind().to([] (SLContext_sptr slc) { return new TestA(slc); }).asTransient(); 237 | auto slc = sl->getContext(); 238 | 239 | auto a = slc->resolve(); 240 | 241 | REQUIRE(a->getIt() == "TestA"); 242 | 243 | auto b = slc->resolve(); 244 | 245 | REQUIRE(b->getIt() == "TestA"); 246 | REQUIRE(a != b); 247 | REQUIRE(a->contextPath == "ITest->"); 248 | } 249 | 250 | SECTION("Binding to singleton function") { 251 | sl->bind().to([] (SLContext_sptr slc) { return new TestA(slc); }).asSingleton(); 252 | auto slc = sl->getContext(); 253 | 254 | auto a = slc->resolve(); 255 | 256 | REQUIRE(a->getIt() == "TestA"); 257 | 258 | auto b = slc->resolve(); 259 | 260 | REQUIRE(a == b); 261 | REQUIRE(a->contextPath == "ITest->"); 262 | } 263 | 264 | SECTION("Nested locator") { 265 | sl->bind().to(); 266 | auto slc = sl->getContext(); 267 | 268 | auto child1 = sl->enter(); 269 | auto child2 = sl->enter(); 270 | 271 | child1->bind().to(); // This should not throw, it should override its parent 272 | 273 | auto b = child1->getContext()->resolve(); 274 | auto a = child2->getContext()->resolve(); 275 | 276 | REQUIRE(a != b); 277 | REQUIRE(a->getIt() == "TestA"); 278 | REQUIRE(a->contextPath == "ITest->"); 279 | REQUIRE(b->getIt() == "TestB"); 280 | REQUIRE(b->contextPath == "ITest->"); 281 | } 282 | 283 | SECTION("Module loading") { 284 | sl->modules().add().add(); 285 | auto slc = sl->getContext(); 286 | 287 | auto a = slc->resolve(); 288 | auto c = slc->resolve(); 289 | 290 | REQUIRE(a->getIt() == "TestA"); 291 | REQUIRE(c->getIt() == "TestC"); 292 | REQUIRE(c->test->getIt() == "TestA"); 293 | REQUIRE(c->test == a); 294 | } 295 | 296 | SECTION("Binding to constant interface") { 297 | const TestNoSL ta = TestNoSL(); 298 | 299 | sl->bind().toInstance(std::shared_ptr(&ta, ServiceLocator::NoDelete)); 300 | auto slc = sl->getContext(); 301 | 302 | auto a = slc->tryResolve(); 303 | 304 | REQUIRE(a != nullptr); 305 | } 306 | 307 | SECTION("Resolve All bindings of type") { 308 | sl->bind("A").to(); 309 | sl->bind("B").to(); 310 | auto slc = sl->getContext(); 311 | 312 | std::vector> all; 313 | slc->resolveAll(&all); 314 | REQUIRE(all.size() == 2); 315 | REQUIRE(all[0]->getIt() == "TestA"); 316 | REQUIRE(all[1]->getIt() == "TestB"); 317 | } 318 | 319 | SECTION("Eager binding") { 320 | sl->bind().toSelfNoDependancy().asSingleton().eagerly(); 321 | 322 | REQUIRE(TestEagerCount == 0); 323 | 324 | // The binding will instantiate when we call getContext() 325 | auto slc = sl->getContext(); 326 | 327 | REQUIRE(TestEagerCount == 1); 328 | } 329 | } 330 | } 331 | 332 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CPPServiceLocator 2 | A header only C++11 Dependency Injector 3 | 4 | Inspired by .NET NInject but by no means anywhere near as sophisticated. 5 | 6 | Supports basic binding to self, interface to implementation class, named bindings, function bindings, instance bindings, singletons, eager bindings, aliases and modules. 7 | 8 | # Usage 9 | Basics, define interfaces (abstract classes) which client code will use 10 | 11 | ```c++ 12 | class IFoo { 13 | public: 14 | virtual void fooIt() = 0; 15 | }; 16 | ``` 17 | 18 | have other code declare dependency in their constructors 19 | 20 | ```c++ 21 | class Bar { 22 | private: 23 | std::shared_ptr _foo; 24 | public: 25 | Bar(std::shared_ptr foo) : _foo(foo) { 26 | } 27 | void doFoo() { 28 | _foo->fooIt(); 29 | } 30 | }; 31 | ``` 32 | 33 | declare implementation classes 34 | 35 | ```c++ 36 | class RedFoo : public IFoo { 37 | public: 38 | void fooIt() override { 39 | std::cout << "RedFoo!\n"; 40 | } 41 | }; 42 | ``` 43 | 44 | declare the bindings in SLModules 45 | 46 | ```c++ 47 | // RedFooSLModule is intimate with RedFoo, it knows what dependencies RedFoo has (in this case none) 48 | class RedFooSLModule : public ServiceLocator::Module { 49 | public: 50 | void load() override { 51 | bind().to([] (SLContext_sptr slc) { 52 | return new RedFoo(); 53 | }); 54 | } 55 | }; 56 | 57 | // BarSLModule is intimate with Bar, it knows what dependencies Bar has .. 58 | class BarSLModule : public ServiceLocator::Module { 59 | public: 60 | void load() override { 61 | bind().toSelf([] (SLContext_ptr slc) { 62 | return new Bar( 63 | slc->resolve() 64 | ); 65 | }) 66 | } 67 | }; 68 | ``` 69 | 70 | load the modules at startup (use configuration to choose which modules are loaded = nice) 71 | 72 | ```c++ 73 | auto sl = ServiceLocator::create(); 74 | sl->modules().add().add(); 75 | ``` 76 | 77 | and request your root object(s) 78 | 79 | ```c++ 80 | auto slc = sl->getContext(); 81 | auto bar = slc->resolve(); 82 | ``` 83 | 84 | # Why is it called ServiceLocator but you said it does Dependency Injection? 85 | The ServiceLocator class does not do Dependency Injection on its own, which is why I chose not to call it a DependencyInjector - the Dependency Injection occurs by how you code your bindings. Using the lambda function bindings to return "new" instances is where the Dependency Injection occurs. It's not Reflection, but it works really well (see above, examples/example_dependency_injector and tests/) 86 | 87 | # Aliases 88 | Each bind only allows 1 interface to 1 implementation. Use aliases to bind multiple interfaces to 1 implementation :- 89 | 90 | ```c++ 91 | bind().toSelf([] (SLContext_sptr) { return new Foo(); }); 92 | bind().alias(); 93 | bind().alias(); 94 | ``` 95 | 96 | # Singleton or Transient 97 | Currently only Transient (default) (new instance on every resolve) and Singleton (same instance globally) are supported. 98 | 99 | ```c++ 100 | bind().to([] (SLContext_sptr slc) { return new Foo(); }).asSingleton(); 101 | ``` 102 | 103 | # Named bindings 104 | Binding an un-named interface more than once will (within any given ServiceLocator) will throw a DuplicateBindingException, named bindings allow multiples 105 | 106 | ```c++ 107 | bind("RedFoo").to([] (SLContext_sptr slc) { return RedFoo(); }); 108 | bind("BlueFoo").to([] (SLContext_sptr slc) { return BlueFoo(); }); 109 | ``` 110 | 111 | Given above, both bindings can be resolved with resolveAll 112 | 113 | ```c++ 114 | std::vector> foos; 115 | slc->resolveAll(&foos); 116 | ``` 117 | 118 | or individually given their name 119 | 120 | ```c++ 121 | auto redFoo = slc->resolve("RedFoo"); 122 | auto blueFoo = slc->resolve("BlueFoo"); 123 | ``` 124 | 125 | # Child ServiceLocators 126 | A root level ServiceLocator is created using 127 | 128 | ```c++ 129 | auto parent = ServiceLocator::create(); 130 | ``` 131 | 132 | child ServiceLocators can be created (deeply nested if needed) 133 | 134 | ```c++ 135 | auto child = parent->enter(); 136 | ``` 137 | 138 | bindings within a child do not affect its parent(s), in fact child bindings can override their parent bindings. 139 | 140 | ```c++ 141 | parent->bind().toNoDependency(); 142 | parent->bind().toNoDependency(); 143 | child->bind().toNoDependency(); 144 | ``` 145 | 146 | A child will attempt to resolve within itself first and walk its parent chain until a binding is found before erroring if binding is not found 147 | 148 | ```c++ 149 | auto will_be_BlueFoo = child->resolve(); 150 | auto will_be_RedFoo = parent->resolve(); 151 | auto will_be_GreenBar = child->resolve(); 152 | ``` 153 | 154 | # Circular dependency detection 155 | 156 | It will automatically detect circular dependency between bindings, eg 157 | 158 | ```c++ 159 | class Foo : public IFoo { 160 | private: 161 | sptr _bar; 162 | public: 163 | Foo(sptr bar) : _bar(bar) { 164 | } 165 | }; 166 | 167 | class Bar : public IBar { 168 | private: 169 | sptr _foo; 170 | public: 171 | Bar(sptr foo) : _foo(foo) { 172 | } 173 | }; 174 | 175 | bind().to([] (SLContext_sptr slc) { return new Foo(slc->resolve()); }).asSingleton(); 176 | bind().to([] (SLContext_sptr slc) { return new Bar(slc->resolve()); }).asSingleton(); 177 | 178 | auto bar = slc->resolve(); // will throw CircularDependencyException with a message showing the dependency path 179 | ``` 180 | 181 | # Working around Circular dependency - Property injection 182 | 183 | It is ofcourse better to design your system such that circular dependencies do not occur, but I have found this is sometimes harder than the alternative which is to use Property Injection. Property Injection resolves the issue since you make 1 of your classes not take its dependency through construction, allowing it to be instantiated and injected into the other class dependant classes constructor, on completion Property Injection resolves the first classes dependency :- 184 | 185 | ```c++ 186 | class Foo : public IFoo { 187 | private: 188 | sptr _bar; 189 | public: 190 | void setBar(sptr bar) { _bar = bar; } 191 | }; 192 | 193 | bind().to([] (SLContext_sptr slc) { 194 | auto foo = new Foo(); 195 | slc->afterResolve([foo] (SLContext_sptr slc) { 196 | foo->setBar(slc->resolve()); 197 | }); 198 | return foo; 199 | }).asSingleton(); 200 | ``` 201 | 202 | The *afterResolve* method queues a call to the lambda after the root object has been instantiated, avoiding the circular dependency. 203 | 204 | Ofcourse the other problem created here is that we now have 2 objects Foo and Bar which hold a shared_ptr reference to each other, even when the ServiceLocator is released (at the end of the program) these 2 objects will continue their lives. In this case one of them would need to explicitly release the other 205 | 206 | ```c++ 207 | void onExit() { 208 | foo->setBar(nullptr); 209 | } 210 | ``` 211 | 212 | # sptr -> std::shared_ptr 213 | At the moment ServiceLocator uses std::shared_ptr to handle instance life times, Singletons are held in memory via a cached std::shared_ptr and all instances are resolved to std::shared_ptr 214 | 215 | Although untested, it is possible to use a different *shared_ptr* implementation by defining 216 | 217 | ```c++ 218 | #define SERVICELOCATOR_SPTR 219 | template 220 | using sptr = boost::shared_ptr; 221 | 222 | template 223 | using const_sptr = boost::shared_ptr; 224 | 225 | template 226 | using wptr = boost::weak_ptr; 227 | 228 | template 229 | using uptr = boost::unique_ptr; 230 | ``` 231 | 232 | before including "ServiceLocator.hpp" 233 | 234 | # Using externally allocated instances 235 | It is possible to have ServiceLocator bind an externally allocated instance using the *NoDelete* deallocation method. This allows these instances lifetime to be controlled externally whilst still allowing them to be ServiceLocator injected. 236 | 237 | ```c++ 238 | Poco::AutoPtr foo = GetFoo(); 239 | sl->bind().toInstance(foo.get(), ServiceLocator::NoDelete); 240 | 241 | auto foo = slc->resolve(); 242 | ``` 243 | 244 | internally the instance is managed using a std::shared_ptr (*sptr*) but will call the *NoDelete* method (which does nothing) when the shared_ptr reference count reaches 0 allowing the Poco::AutoPtr to continue lifetime management. 245 | 246 | Ofcourse when doing this you need to gaurantee that the externally allocated instance does not release the instance during the lifetime of the ServiceLocator. 247 | 248 | 249 | 250 | # Why another Dependency Injection library 251 | Firstly, there are not that many for C++ in general. There are amongst a couple of others, Google Fruit and Boost DI. Boost DI requires C++14 so I did not even look at this (my project is strictly C++11 limited) and Google Fruit I frankly found too hard to understand how to use - sure, it's almost definitely me, but I am quite familiar with .NET Ninject and was struggling to map concepts to Google Fruit within my deadline. 252 | 253 | Also note, that Google Fruit contaminates your classes with INJECT() macros - not a massive deal but it makes you classes Fruit aware when perhaps they shouldn't be. Outside of using std::shared_ptr my ServiceLocator requires no such contamination of your interfaces or implementation classes. 254 | 255 | So I rolled my own - initially just developed a simple Service Locator - a dictionary of typeids to templated classes - and yes Service Locator is an anti-pattern. I was prepared to wear the anti-pattern drawbacks initially. However after getting this going it became ever more apparent this would be hard work for unit tests and development in general since missing dependencies were not caught until runtime. 256 | 257 | Issue (1) is getting C++ to do any sort of constructor injection. Reflection is not available in C++ which is how NInject does it's magic. 258 | Issue (2) is my classes were ServiceLocator contaminated - they all took a single constructor argument of ServiceLocator* to which they would find their dependencies, this was also bad. 259 | 260 | eg 261 | 262 | ```c++ 263 | #include "ServiceLocator.hpp" // Yikes, ServiceLocator contamination 264 | class Bar { 265 | private: 266 | std::shared_ptr _foo; 267 | public: 268 | // CONTAMINATION - My constructor takes a ServiceLocatorContext*, AND my dependencies are hidden until run-time - ouch 269 | Bar(SLContext_sptr slc) : _foo(slc->resolve()) { 270 | } 271 | }; 272 | ``` 273 | 274 | The anti-pattern is the cause of both issues, and the solution to both is quite simple :- 275 | 276 | a) Move the constructor initialisation into a ServiceLocator Module and declare your constructors with explicit dependencies, this means they are not ServiceLocator contaminated (solves (2)) and now your ServiceLocator Modules are the only place that is ServiceLocator aware and you solve issue (1) since constructors are declaring all dependencies - you get compile errors instead of runtime nullptr's. 277 | 278 | there is no b) 279 | 280 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Steve Fillingham 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /ServiceLocator.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2020 Steve Fillingham 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | #ifndef ServiceLocator_hpp 18 | #define ServiceLocator_hpp 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #ifndef SERVICELOCATOR_SPTR 30 | #define SERVICELOCATOR_SPTR 31 | template 32 | using sptr = std::shared_ptr; 33 | 34 | template 35 | using const_sptr = std::shared_ptr; 36 | 37 | template 38 | using wptr = std::weak_ptr; 39 | 40 | template 41 | using uptr = std::unique_ptr; 42 | #endif 43 | 44 | class ServiceLocatorException { 45 | private: 46 | std::string _message; 47 | 48 | public: 49 | ServiceLocatorException(const std::string& message) : _message(message) { 50 | } 51 | 52 | const std::string& getMessage() const { 53 | return _message; 54 | } 55 | }; 56 | 57 | class DuplicateBindingException : public ServiceLocatorException { 58 | public: 59 | DuplicateBindingException(const std::string& message) : ServiceLocatorException(message) { 60 | } 61 | }; 62 | 63 | class RecursiveResolveException : public ServiceLocatorException { 64 | public: 65 | RecursiveResolveException(const std::string& message) : ServiceLocatorException(message) { 66 | } 67 | }; 68 | 69 | class BindingIssueException : public ServiceLocatorException { 70 | public: 71 | BindingIssueException(const std::string& message) : ServiceLocatorException(message) { 72 | } 73 | }; 74 | 75 | class UnableToResolveException : public ServiceLocatorException { 76 | public: 77 | UnableToResolveException(const std::string& message) : ServiceLocatorException(message) { 78 | } 79 | }; 80 | 81 | class ServiceLocator { 82 | public: 83 | friend class Context; 84 | 85 | class Context { 86 | private: 87 | // Only the root Context will run the AfterResolveList - this allows circular dependancies to 88 | // resolve by using afterResolve property injection 89 | Context* _root; 90 | std::list)>>* _fnAfterResolveList = nullptr; 91 | 92 | Context* _parent; 93 | wptr _sl; 94 | std::type_index _interfaceType; 95 | mutable uptr _interfaceTypeName; 96 | std::string _name; 97 | 98 | uptr _concreteType; 99 | mutable uptr _concreteTypeName; 100 | 101 | 102 | std::string getTypeName(const std::type_index& typeIndex) const { 103 | int status; 104 | auto s = __cxxabiv1::__cxa_demangle (typeIndex.name(), nullptr, nullptr, &status); 105 | std::string result; 106 | switch(status) { 107 | case 0: 108 | result = std::string(s); 109 | break; 110 | case 1: 111 | result = "Memory failure"; 112 | break; 113 | case 2: 114 | result = "Not a mangled name"; 115 | break; 116 | case 3: 117 | result = "Invalid arguments"; 118 | break; 119 | } 120 | if (s) { 121 | delete s; 122 | } 123 | return result; 124 | } 125 | 126 | void checkRecursiveResolve(Context* resolveCtx, Context* compareCtx) { 127 | if (resolveCtx->_interfaceType == compareCtx->_interfaceType && resolveCtx->_name == compareCtx->_name) { 128 | throw RecursiveResolveException("Recursive resolve path = " + resolveCtx->getResolvePath()); 129 | } 130 | if (compareCtx->_parent != nullptr) { 131 | checkRecursiveResolve(resolveCtx, compareCtx->_parent); 132 | } 133 | } 134 | 135 | void afterResolve() { 136 | if (this == _root) { 137 | if (_fnAfterResolveList != nullptr) { 138 | for(auto fn : *_fnAfterResolveList) { 139 | auto ctx = sptr(new Context(_sl)); 140 | fn(ctx); 141 | } 142 | delete _fnAfterResolveList; 143 | _fnAfterResolveList = nullptr; 144 | } 145 | } 146 | } 147 | 148 | public: 149 | Context(Context* root, Context* parent, wptr sl, const std::type_index interfaceType, const std::string& name) : _root(root), _parent(parent), _sl(sl), _interfaceType(interfaceType), _name(name) { 150 | } 151 | 152 | Context(Context* parent, const std::type_index interfaceType, const std::string& name) : Context(parent->_root, parent, parent->_sl, interfaceType, name) { 153 | } 154 | 155 | Context(wptr sl, const std::type_index interfaceType, const std::string& name) : Context(this, nullptr, sl, interfaceType, name) { 156 | } 157 | 158 | Context(wptr sl) : Context(this, nullptr, sl, std::type_index(typeid(void)), "") { 159 | } 160 | 161 | const std::string& getName() const { 162 | return _name; 163 | } 164 | 165 | const std::string& getInterfaceTypeName() const { 166 | if (_interfaceTypeName == nullptr) { 167 | _interfaceTypeName = uptr(new std::string(getTypeName(_interfaceType))); 168 | } 169 | return *_interfaceTypeName; 170 | } 171 | 172 | const std::type_index& getInterfaceTypeIndex() const { 173 | return _interfaceType; 174 | } 175 | 176 | void setConcreteType(const std::type_index& concreteType) { 177 | if (_concreteType != nullptr) { 178 | throw BindingIssueException("Concrete type on Context already set"); 179 | } 180 | _concreteType = uptr(new std::type_index(concreteType)); 181 | } 182 | 183 | const std::string& getConcreteTypeName() const { 184 | if (_concreteTypeName == nullptr) { 185 | _concreteTypeName = uptr(new std::string(getTypeName(*_concreteType))); 186 | } 187 | return *_concreteTypeName; 188 | } 189 | 190 | const std::type_index& getConcreteTypeIndex() const { 191 | return *_concreteType; 192 | } 193 | 194 | Context* getParent() const { 195 | return _parent; 196 | } 197 | 198 | sptr getServiceLocator() const { 199 | return _sl.lock(); 200 | } 201 | 202 | // Resolve a named interface, throws if not able to resolve 203 | template 204 | sptr resolve(const std::string& named) { 205 | auto ctx = sptr(new Context(this, std::type_index(typeid(IFace)), named)); 206 | checkRecursiveResolve(ctx.get(), this); 207 | auto ptr = _sl.lock()->_resolve(ctx); 208 | afterResolve(); 209 | return ptr; 210 | } 211 | 212 | // Resolve an interface, throws if not able to resolve 213 | template 214 | sptr resolve() { 215 | auto ctx = sptr(new Context(this, std::type_index(typeid(IFace)), "")); 216 | checkRecursiveResolve(ctx.get(), this); 217 | auto ptr = _sl.lock()->_resolve(ctx); 218 | afterResolve(); 219 | return ptr; 220 | } 221 | 222 | template 223 | void resolveAll(std::vector>* all) { 224 | _sl.lock()->_visitAll([this, all] (sptr::shared_ptr_binding> binding) { 225 | auto ctx = sptr(new Context(this, std::type_index(typeid(IFace)), "")); 226 | checkRecursiveResolve(ctx.get(), this); 227 | all->push_back(binding->get(ctx)); 228 | }); 229 | afterResolve(); 230 | } 231 | 232 | // Determine if a named interface can be resolved 233 | template 234 | bool canResolve(const std::string& named) { 235 | auto ctx = sptr(new Context(this, std::type_index(typeid(IFace)), named)); 236 | return _sl.lock()->_canResolve(ctx); 237 | } 238 | 239 | // Determine if an interface can be resolved 240 | template 241 | bool canResolve() { 242 | auto ctx = sptr(new Context(this, std::type_index(typeid(IFace)), "")); 243 | return _sl.lock()->_canResolve(ctx); 244 | } 245 | 246 | // Try to resolve a named interface, returns nullptr on failure 247 | template 248 | sptr tryResolve(const std::string& named) { 249 | auto ctx = sptr(new Context(this, std::type_index(typeid(IFace)), named)); 250 | checkRecursiveResolve(ctx.get(), this); 251 | auto ptr = _sl.lock()->_tryResolve(ctx); 252 | afterResolve(); 253 | return ptr; 254 | } 255 | 256 | // Try to resolve an interface, returns nullptr on failure 257 | template 258 | sptr tryResolve() { 259 | auto ctx = sptr(new Context(this, std::type_index(typeid(IFace)), "")); 260 | checkRecursiveResolve(ctx.get(), this); 261 | auto ptr = _sl.lock()->_tryResolve(ctx); 262 | afterResolve(); 263 | return ptr; 264 | } 265 | 266 | template 267 | std::function(const std::string&)> provider() { 268 | // We lock the weak_ptr to our ServiceLocator, the lock returns a shared_ptr which will keep 269 | // it alive into the returned lambda via the capture of sl 270 | auto sl = _sl.lock(); 271 | return [sl] (const std::string& name = "") { 272 | auto ctx = sptr(new Context(sl, std::type_index(typeid(IFace)), name)); 273 | // Don't need to check for recursive resolve since this is a provider (root) call 274 | auto ptr = sl->_resolve(ctx); 275 | // ctx is root Context, it can afterResolve 276 | ctx->afterResolve(); 277 | return ptr; 278 | }; 279 | } 280 | 281 | template 282 | std::function(const std::string&)> tryProvider() { 283 | // We lock the weak_ptr to our ServiceLocator, the lock returns a shared_ptr which will keep 284 | // it alive into the returned lambda via the capture of sl 285 | auto sl = _sl.lock(); 286 | return [sl] (const std::string& name = "") { 287 | auto ctx = sptr(new Context(sl, std::type_index(typeid(IFace)), name)); 288 | // Don't need to check for recursive resolve since this is a tryProvider (root) call 289 | auto ptr = sl->_tryResolve(ctx); 290 | // ctx is root Context, it can afterResolve 291 | ctx->afterResolve(); 292 | return ptr; 293 | }; 294 | } 295 | 296 | std::string getResolvePath() const { 297 | std::string path = ""; 298 | // Note the root Parent has a IFace which is not real, just cannot have no interface defined 299 | if (_parent != nullptr && _parent->_parent != nullptr) { 300 | path = _parent->getResolvePath() + " -> "; 301 | } 302 | 303 | path += "resolve<" + getInterfaceTypeName() + ">(" + _name + ")"; 304 | 305 | if (_concreteType != nullptr) { 306 | path += ".to<" + getConcreteTypeName() + ">"; 307 | } 308 | 309 | return path; 310 | } 311 | 312 | void afterResolve(std::function)> fnAfterResolve) { 313 | if (_root->_fnAfterResolveList == nullptr) { 314 | _root->_fnAfterResolveList = new std::list)>>(); 315 | } 316 | _root->_fnAfterResolveList->push_back(fnAfterResolve); 317 | } 318 | }; 319 | 320 | private: 321 | class AnyServiceLocator { 322 | public: 323 | virtual ~AnyServiceLocator() { 324 | } 325 | 326 | class loose_binding { 327 | public: 328 | virtual ~loose_binding() { 329 | } 330 | 331 | virtual void eagerBind(sptr slc) = 0; 332 | }; 333 | }; 334 | 335 | template 336 | class TypedServiceLocator : public AnyServiceLocator { 337 | public: 338 | class shared_ptr_binding : public loose_binding { 339 | private: 340 | std::function(sptr)> _fnGet; 341 | std::function(sptr)> _fnCreate; 342 | 343 | // Note, this is used during binding only .. 344 | std::list* _eagerBindings; 345 | 346 | public: 347 | class eagerly_clause { 348 | private: 349 | shared_ptr_binding* _ibinding; 350 | 351 | public: 352 | eagerly_clause(shared_ptr_binding* ibinding) : _ibinding(ibinding) { 353 | } 354 | 355 | void eagerly() { 356 | _ibinding->_eagerBindings->push_back(_ibinding); 357 | } 358 | }; 359 | 360 | class as_clause { 361 | private: 362 | sptr _singleton; 363 | shared_ptr_binding* _ibinding; 364 | 365 | public: 366 | as_clause(shared_ptr_binding* ibinding) : _ibinding(ibinding) { 367 | } 368 | 369 | eagerly_clause& asSingleton() { 370 | // on 1st call we create the singleton .. 371 | _ibinding->_fnGet = [this] (sptr slc) { 372 | _singleton = _ibinding->_fnCreate(slc); 373 | 374 | auto singleton = _singleton; 375 | 376 | // rebind fnGet to return the new singleton 377 | _ibinding->_fnGet = [this] (sptr slc) { 378 | return _singleton; 379 | }; 380 | 381 | return singleton; 382 | }; 383 | return _ibinding->_eagerly_clause; 384 | } 385 | 386 | void asTransient() { 387 | _ibinding->_fnGet = _ibinding->_fnCreate; 388 | } 389 | }; 390 | 391 | class to_clause { 392 | private: 393 | shared_ptr_binding* _ibinding; 394 | 395 | public: 396 | to_clause(shared_ptr_binding* ibinding) : _ibinding(ibinding) { 397 | } 398 | 399 | void toInstance(sptr instance) { 400 | // fnCreate is not needed, we always return 'instance' 401 | _ibinding->_fnGet = [instance] (sptr slc) { 402 | return instance; 403 | }; 404 | } 405 | 406 | void toInstance(IFace* instance) { 407 | auto cached = sptr(instance); 408 | // fnCreate is not needed, we always return 'instance' 409 | _ibinding->_fnGet = [cached] (sptr slc) { 410 | return cached; 411 | }; 412 | } 413 | 414 | as_clause& toSelf() { 415 | _ibinding->_fnGet = _ibinding->_fnCreate = [] (sptr slc) { 416 | slc->setConcreteType(std::type_index(typeid(IFace))); 417 | return sptr(new IFace(slc)); 418 | }; 419 | return _ibinding->_as_clause; 420 | } 421 | 422 | as_clause& toSelfNoDependancy() { 423 | _ibinding->_fnGet = _ibinding->_fnCreate = [] (sptr slc) { 424 | slc->setConcreteType(std::type_index(typeid(IFace))); 425 | return sptr(new IFace()); 426 | }; 427 | return _ibinding->_as_clause; 428 | } 429 | 430 | template 431 | as_clause& to() { 432 | _ibinding->_fnGet = _ibinding->_fnCreate = [] (sptr slc) { 433 | slc->setConcreteType(std::type_index(typeid(TImpl))); 434 | return sptr(new TImpl(slc)); 435 | }; 436 | return _ibinding->_as_clause; 437 | } 438 | 439 | template 440 | as_clause& toNoDependancy() { 441 | _ibinding->_fnGet = _ibinding->_fnCreate = [] (sptr slc) { 442 | slc->setConcreteType(std::type_index(typeid(TImpl))); 443 | return sptr(new TImpl()); 444 | }; 445 | return _ibinding->_as_clause; 446 | } 447 | 448 | template 449 | as_clause& to(std::function(sptr)> fnCreate) { 450 | _ibinding->_fnGet = _ibinding->_fnCreate = [fnCreate] (sptr slc) { 451 | slc->setConcreteType(std::type_index(typeid(TImpl))); 452 | return fnCreate(slc); 453 | }; 454 | return _ibinding->_as_clause; 455 | } 456 | 457 | // similar to above, except caller can return IFace* instead of sptr 458 | template 459 | as_clause& to(std::function)> fnCreate) { 460 | _ibinding->_fnGet = _ibinding->_fnCreate = [fnCreate] (sptr slc) { 461 | slc->setConcreteType(std::type_index(typeid(TImpl))); 462 | // create sptr around the returned ptr 463 | auto ptr = fnCreate(slc); 464 | return sptr(ptr); 465 | }; 466 | return _ibinding->_as_clause; 467 | } 468 | 469 | as_clause& alias(const std::string& name) { 470 | _ibinding->_fnGet = _ibinding->_fnCreate = [name] (sptr slc) { 471 | return slc->resolve(name); 472 | }; 473 | return _ibinding->_as_clause; 474 | } 475 | 476 | template 477 | as_clause& alias() { 478 | _ibinding->_fnGet = _ibinding->_fnCreate = [] (sptr slc) { 479 | return slc->resolve(slc->getName()); 480 | }; 481 | return _ibinding->_as_clause; 482 | } 483 | 484 | template 485 | as_clause& alias(const std::string& name) { 486 | _ibinding->_fnGet = _ibinding->_fnCreate = [name] (sptr slc) { 487 | return slc->resolve(name); 488 | }; 489 | return _ibinding->_as_clause; 490 | } 491 | 492 | }; 493 | 494 | to_clause _to_clause; 495 | as_clause _as_clause; 496 | eagerly_clause _eagerly_clause; 497 | 498 | public: 499 | shared_ptr_binding(std::list* eagerBindings) 500 | : 501 | _eagerBindings(eagerBindings), 502 | _to_clause(this), 503 | _as_clause(this), 504 | _eagerly_clause(this) { 505 | } 506 | 507 | virtual sptr get(sptr slc) const { 508 | return _fnGet(slc); 509 | } 510 | 511 | void eagerBind(sptr slc) override { 512 | auto ctx = sptr(new Context(slc.get(), std::type_index(typeid(IFace)), "")); 513 | _fnGet(ctx); 514 | } 515 | }; 516 | 517 | std::map> _bindings; 518 | 519 | public: 520 | typename shared_ptr_binding::to_clause& bind(const std::string& name, std::list* eagerBindings) { 521 | if (canResolve(name)) { 522 | throw DuplicateBindingException(std::string("Duplicate binding for <") + typeid(IFace).name() + "> named " + name); 523 | } 524 | 525 | auto binding = sptr(new shared_ptr_binding(eagerBindings)); 526 | 527 | // (non const) IFace binding 528 | _bindings.insert(std::pair>(name, binding)); 529 | 530 | return binding->_to_clause; 531 | } 532 | 533 | bool canResolve(const std::string& name) { 534 | return _bindings.find(name) != _bindings.end(); 535 | } 536 | 537 | sptr tryResolve(const std::string& name, sptr slc) { 538 | auto binding = _bindings.find(name); 539 | if (binding == _bindings.end()) { 540 | return nullptr; 541 | } 542 | auto ibinding = std::dynamic_pointer_cast(binding->second); 543 | 544 | return ibinding->get(slc); 545 | } 546 | 547 | void visitAll(std::function::shared_ptr_binding>)> fnVisit) { 548 | for(auto binding : _bindings) { 549 | auto ibinding = std::dynamic_pointer_cast(binding.second); 550 | fnVisit(ibinding); 551 | } 552 | } 553 | }; 554 | 555 | // Named locator bindings (simple map from string to NamedServiceLocator) 556 | std::map _typed_locators; 557 | mutable std::list _eagerBindings; 558 | 559 | sptr _parent; 560 | sptr _context; 561 | 562 | // We store a weak_ptr to ourselves so that we can create shared_ptr's from it when we enter() child 563 | // locators 564 | wptr _this; 565 | 566 | template 567 | TypedServiceLocator* getTypedServiceLocator(bool createIfRequired) { 568 | auto typeIndex = std::type_index(typeid(IFace)); 569 | auto find = _typed_locators.find(typeIndex); 570 | if (find != _typed_locators.end()) { 571 | return dynamic_cast*>(find->second); 572 | } 573 | 574 | if (!createIfRequired) { 575 | return nullptr; 576 | } 577 | 578 | auto nsl = new TypedServiceLocator(); 579 | _typed_locators.insert(std::pair(typeIndex, nsl)); 580 | return nsl; 581 | } 582 | 583 | // Hide default constructor - client should call ::create which returns a shared_ptr version 584 | ServiceLocator() : ServiceLocator(nullptr) { 585 | } 586 | 587 | // Child locators keep a shared_ptr to their parent 588 | ServiceLocator(sptr parent) : _parent(parent) { 589 | } 590 | 591 | // Resolve a named interface, throws if not able to resolve 592 | template 593 | sptr _resolve(sptr slc) { 594 | auto& name = slc->getName(); 595 | auto nsl = getTypedServiceLocator(false); 596 | if (nsl == nullptr) { 597 | if (_parent == nullptr) { 598 | throw UnableToResolveException(std::string("Unable to resolve <") + slc->getInterfaceTypeName() + "> resolve path = " + slc->getResolvePath()); 599 | } 600 | return _parent->_resolve(slc); 601 | } 602 | 603 | auto ptr = nsl->tryResolve(name, slc); 604 | if (ptr == nullptr) { 605 | if (_parent == nullptr) { 606 | throw UnableToResolveException(std::string("Unable to resolve <") + slc->getInterfaceTypeName() + "> resolve path = " + slc->getResolvePath()); 607 | } 608 | return _parent->_resolve(slc); 609 | } 610 | 611 | return ptr; 612 | } 613 | 614 | // Resolve a named interface, throws if not able to resolve 615 | template 616 | void _visitAll(std::function::shared_ptr_binding>)> fnVisit) { 617 | auto nsl = getTypedServiceLocator(false); 618 | if (nsl != nullptr) { 619 | nsl->visitAll(fnVisit); 620 | } 621 | 622 | if (_parent != nullptr) { 623 | _parent->_visitAll(fnVisit); 624 | } 625 | } 626 | 627 | template 628 | bool _canResolve(sptr slc) { 629 | auto nsl = getTypedServiceLocator(false); 630 | if (nsl == nullptr) { 631 | if (_parent == nullptr) { 632 | return false; 633 | } 634 | 635 | return _parent->_canResolve(slc); 636 | } 637 | 638 | return nsl->canResolve(slc->getName()); 639 | } 640 | 641 | // Try to resolve a named interface, returns nullptr on failure 642 | template 643 | sptr _tryResolve(sptr slc) { 644 | auto nsl = getTypedServiceLocator(false); 645 | if (nsl == nullptr) { 646 | if (_parent == nullptr) { 647 | return nullptr; 648 | } 649 | 650 | return _parent->_tryResolve(slc); 651 | } 652 | 653 | auto ptr = nsl->tryResolve(slc->getName(), slc); 654 | if (ptr == nullptr && _parent != nullptr) { 655 | return _parent->_tryResolve(slc); 656 | } 657 | return ptr; 658 | } 659 | 660 | public: 661 | // Create a root ServiceLocator 662 | static sptr create() { 663 | auto slp = sptr(new ServiceLocator()); 664 | 665 | // Keep a weak reference to ourselves (weird) - have to do this in order to be able to 666 | // create children which have shared_ptr's to their parents - you cannot create 2 shared_ptr 667 | // instances from a raw pointer you will crash on 2nd shared_ptr going out of scope and deleting 668 | // the instance which has already been deleted by the 1st shared_ptr going out of scope 669 | slp->_this = slp; 670 | slp->_context = sptr(new Context(slp)); 671 | 672 | return slp; 673 | } 674 | 675 | virtual ~ServiceLocator() { 676 | } 677 | 678 | // Create a child ServiceLocator. Children can override parent bindings or add new ones (they cannot delete 679 | // a parent binding). Children will revert to their parents for unresolved bindings 680 | sptr enter() { 681 | auto slp = sptr(new ServiceLocator(sptr(_this))); 682 | slp->_this = slp; 683 | slp->_context = sptr(new Context(slp)); 684 | return slp; 685 | } 686 | 687 | // Create a named binding 688 | template 689 | typename TypedServiceLocator::shared_ptr_binding::to_clause& bind(const std::string& named) { 690 | auto nsl = getTypedServiceLocator(true); 691 | 692 | return nsl->bind(named, &_eagerBindings); 693 | } 694 | 695 | // Create a binding 696 | template 697 | typename TypedServiceLocator::shared_ptr_binding::to_clause& bind() { 698 | auto nsl = getTypedServiceLocator(true); 699 | 700 | return nsl->bind("", &_eagerBindings); 701 | } 702 | 703 | sptr getContext() const { 704 | if (_eagerBindings.size() > 0) { 705 | for(auto eagerBinding : _eagerBindings) { 706 | eagerBinding->eagerBind(_context); 707 | } 708 | _eagerBindings.clear(); 709 | } 710 | return _context; 711 | } 712 | 713 | 714 | class module_clause; 715 | 716 | // Derive from this to create custom Modules to load from 717 | class Module { 718 | friend class module_clause; 719 | 720 | protected: 721 | sptr _sl; 722 | 723 | public: 724 | // Create a named binding 725 | template 726 | typename TypedServiceLocator::shared_ptr_binding::to_clause& bind(const std::string& named) { 727 | return _sl->bind(named); 728 | } 729 | 730 | // Create a binding 731 | template 732 | typename TypedServiceLocator::shared_ptr_binding::to_clause& bind() { 733 | return _sl->bind(); 734 | } 735 | 736 | public: 737 | virtual void load() = 0; 738 | }; 739 | 740 | 741 | // Simple module loading syntax 742 | // modules().add().add().... 743 | 744 | class module_clause { 745 | private: 746 | mutable sptr _sl; 747 | 748 | public: 749 | module_clause(sptr sl) : _sl(sl) { 750 | } 751 | 752 | template 753 | module_clause& add() { 754 | auto module = uptr(new TModule()); 755 | module->_sl = _sl; 756 | 757 | module->load(); 758 | 759 | return *this; 760 | } 761 | 762 | module_clause& add(ServiceLocator::Module&& module) { 763 | module._sl = _sl; 764 | 765 | module.load(); 766 | 767 | return *this; 768 | } 769 | 770 | module_clause& add(ServiceLocator::Module& module) { 771 | module._sl = _sl; 772 | 773 | module.load(); 774 | 775 | return *this; 776 | } 777 | 778 | }; 779 | 780 | sptr _module_clause; 781 | module_clause& modules() { 782 | if (_module_clause == nullptr) { 783 | _module_clause = sptr(new module_clause(sptr(_this))); 784 | } 785 | return *_module_clause; 786 | } 787 | 788 | 789 | // This function is used to allow ServiceLocator to "manage" objects which are actually owned outside 790 | // of ServiceLocator's realm (ie ServiceLocator should not be able to delete the instance through shared_ptr 791 | // reference decrementing to 0) 792 | // 793 | // This is useful when something else owns an object we need to Inject, ServiceLocator always returns 794 | // shared_ptr objects. In order to make ServiceLocator not delete the alien instance, bind like so 795 | // 796 | // bind().toInstance(sptr(alienObj, ServiceLocator::NoDelete)); 797 | // 798 | static void NoDelete(const void*) { 799 | } 800 | }; 801 | 802 | typedef sptr SLContext_sptr; 803 | 804 | #endif /* ServiceLocator_hpp */ 805 | --------------------------------------------------------------------------------