1 /* 2 * Copyright 2014 Google Inc. All rights reserved. 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 FRUIT_COMPONENT_H 18 #define FRUIT_COMPONENT_H 19 20 // This include is not required here, but having it here shortens the include trace in error messages. 21 #include <fruit/impl/injection_errors.h> 22 23 #include <fruit/fruit_forward_decls.h> 24 #include <fruit/impl/bindings.h> 25 #include <fruit/impl/component_functors.defn.h> 26 #include <fruit/impl/component_storage/component_storage.h> 27 #include <fruit/impl/component_storage/partial_component_storage.h> 28 #include <fruit/impl/meta/component.h> 29 30 namespace fruit { 31 32 /** 33 * A component (aka module) represents a collection of bindings. 34 * You can think of a Component object as a UML component. 35 * 36 * The parameters can be of the form <P...> or <Required<R...>, P...> where: 37 * * R... are the required types (types required to inject some types in P... but that are not provided by this 38 * Component), if any 39 * * P... are the types provided by this Component. 40 * No type can appear twice, not even once in R and once in P. 41 * 42 * See PartialComponent below for how to construct a Component. 43 */ 44 template <typename... Params> 45 class Component { 46 public: 47 Component(Component&&) noexcept = default; 48 49 Component& operator=(Component&&) = delete; 50 Component& operator=(const Component&) = delete; 51 52 /** 53 * Converts a PartialComponent to an arbitrary Component, auto-injecting the missing types (if 54 * any). 55 * This is usually called implicitly when returning a component from a function. See PartialComponent for an example. 56 */ 57 template <typename... Bindings> 58 Component(PartialComponent<Bindings...>&& component) noexcept; // NOLINT(google-explicit-constructor) 59 60 private: 61 // Do not use. Use fruit::createComponent() instead. 62 Component() = default; 63 64 template <typename... Types> 65 friend class Component; 66 67 template <typename... Bindings> 68 friend class PartialComponent; 69 70 template <typename... OtherParams> 71 friend class NormalizedComponent; 72 73 template <typename... OtherParams> 74 friend class Injector; 75 76 template <typename... Bindings> 77 friend class fruit::impl::PartialComponentStorage; 78 79 template <typename Component, typename... Args> 80 friend class fruit::impl::LazyComponentImpl; 81 82 friend struct fruit::impl::ComponentStorageEntry::LazyComponentWithNoArgs; 83 84 template <typename Component, typename... Args> 85 friend class fruit::impl::ComponentInterfaceImpl; 86 87 fruit::impl::ComponentStorage storage; 88 89 using Comp = fruit::impl::meta::Eval<fruit::impl::meta::ConstructComponentImpl(fruit::impl::meta::Type<Params>...)>; 90 91 using Check1 = typename fruit::impl::meta::CheckIfError<Comp>::type; 92 // Force instantiation of Check1. 93 static_assert(true || sizeof(Check1), ""); 94 }; 95 96 /** 97 * Constructs an empty component. 98 * 99 * Example usage: 100 * 101 * fruit::Component<Foo> getFooComponent() { 102 * return fruit::createComponent() 103 * .install(getComponent1) 104 * .install(getComponent2) 105 * .bind<Foo, FooImpl>(); 106 * } 107 * 108 * Since types are auto-injected when needed, just converting this to the desired component can suffice in some cases, 109 * e.g.: 110 * 111 * fruit::Component<Foo> getFooComponent() { 112 * return fruit::createComponent(); 113 * } 114 * 115 * That works if Foo has an Inject typedef or a constructor wrapped in INJECT. 116 */ 117 PartialComponent<> createComponent(); 118 119 /** 120 * A partially constructed component. 121 * 122 * Client code should never write `PartialComponent'; always start the construction of a component with 123 * fruit::createComponent(), and end it by casting the PartialComponent to the desired Component (often done implicitly 124 * by returning a PartialComponent from a function that has Component<...> as the return type). 125 * 126 * The template parameter is used to propagate information about bound types, it is purely an implementation detail; 127 * users of the Fruit library can pretend that this class is not templated, in no case a specific template parameter is 128 * required. All methods of this class return a PartialComponent, which allows to chain method invocations without 129 * declaring a variable of type PartialComponent. 130 * 131 * Example usage: 132 * 133 * fruit::Component<Foo> getFooComponent() { 134 * return fruit::createComponent() 135 * .install(getComponent1) 136 * .install(getComponent2) 137 * .bind<Foo, FooImpl>(); 138 * } 139 * 140 * Note that no variable of type PartialComponent has been declared; this class should only be used for temporary 141 * values. 142 */ 143 template <typename... Bindings> 144 class PartialComponent { 145 public: 146 PartialComponent& operator=(PartialComponent&&) = delete; 147 PartialComponent& operator=(const PartialComponent&) = delete; 148 149 /** 150 * This tells Fruit that "the implementation of I is C". 151 * I must be a base class of C, and it's typically (but not necessarily) an abstract class. 152 * C is typically a concrete class, but it doesn't have to be: for example, if A inherits from B and B inherits from C 153 * you can specify bind<C, B>() and bind<B, A>(). 154 * 155 * The most common use of this is to bind the type I to the type C, for example: 156 * 157 * class MyInterface { 158 * public: 159 * virtual void foo() = 0; 160 * }; 161 * 162 * class MyImplementation { 163 * public: 164 * INJECT(MyImplementation()) {} 165 * 166 * void foo() { 167 * ... 168 * } 169 * }; 170 * 171 * fruit::Component<MyInterface> getMyInterfaceComponent() { 172 * return fruit::createComponent() 173 * .bind<MyInterface, MyImplementation>(); 174 * } 175 * 176 * The implementation class can be bound in any way, it doesn't need to be bound using constructor injection as above 177 * (although that's a very common use case). 178 * 179 * You can bind an interface to a type bound using a constant binding (see the bindInstance method that takes a const& 180 * for more details), however the interface will then also be considered bound with a constant binding, and you must 181 * declare that in the returned Component's type. For example: 182 * 183 * fruit::Component<const MyInterface> getMyInterfaceComponent() { 184 * static const MyImplementation my_implementation = MyImplementation(); 185 * return fruit::createComponent() 186 * .bindInstance(my_implementation) 187 * .bind<MyInterface, MyImplementation>(); 188 * } 189 * 190 * In addition to binding the type I to the type C, a `bind()` can also be used to bind a 191 * std::function<std::unique_ptr<I>(Args...)> to a std::function<std::unique_ptr<C>(Args...)> or a 192 * std::function<C(Args...)>. For example: 193 * 194 * fruit::Component<std::function<std::unique_ptr<MyInterface>(int)>> getIFactoryComponent() { 195 * static const std::function<MyImplementation(int)> cFactory = [](int n) { return MyImplementation(n); }; 196 * return fruit::createComponent() 197 * .bind<MyInterface, MyImplementation>() 198 * .bindInstance(cFactory); 199 * } 200 * 201 * Or alternatively you can do the same using constructor injection: 202 * 203 * class MyImplementation { 204 * public: 205 * INJECT(MyImplementation(ASSISTED(int) n)) 206 * : n(n) { 207 * } 208 * ... 209 * }; 210 * 211 * fruit::Component<std::function<std::unique_ptr<MyInterface>(int)>> getIFactoryComponent() { 212 * return fruit::createComponent() 213 * .bind<MyInterface, MyImplementation>(); 214 * } 215 * 216 * Fruit determines the actual binding(s) to generate based on the types you declare as provided in the returned 217 * Component<> type (e.g. in the last example std::function<std::unique_ptr<MyInterface>(int)> is declared as provided 218 * so Fruit will generate a factory binding instead of a normal MyInterface->MyImplementation binding. 219 * 220 * Fruit can also detect types that are needed for constructor/provider/factory bindings, and it will then use that 221 * information to determine the desired binding. For example: 222 * 223 * class MyImplementation { 224 * public: 225 * INJECT(MyImplementation(ASSISTED(int) n)) 226 * : n(n) { 227 * } 228 * ... 229 * }; 230 * 231 * class Foo { 232 * private: 233 * std::function<std::unique_ptr<MyInterface>(int)> factory; 234 * public: 235 * INJECT(Foo(std::function<std::unique_ptr<MyInterface>(int)> factory)) 236 * : factory(factory) { 237 * } 238 * }; 239 * 240 * fruit::Component<Foo> getIFactoryComponent() { 241 * return fruit::createComponent() 242 * // We want to bind Foo, which requires std::function<std::unique_ptr<MyInterface>(int)>. 243 * // So std::function<std::unique_ptr<MyInterface>(int)> will be bound to 244 * // std::function<std::unique_ptr<MyImplementation>(int)>, and that will be bound using constructor injection. 245 * .bind<MyInterface, MyImplementation>(); 246 * } 247 * 248 * All these cases support annotated injection, just wrap I and/or C in fruit::Annotated<> if desired. For example: 249 * 250 * struct MyAnnotation{}; 251 * 252 * fruit::Component<fruit::Annotated<MyAnnotation, MyInterface>> getMyInterfaceComponent() { 253 * return fruit::createComponent() 254 * .bind<fruit::Annotated<MyAnnotation, MyInterface>, MyImplementation>(); 255 * } 256 */ 257 template <typename I, typename C> 258 PartialComponent<fruit::impl::Bind<I, C>, Bindings...> bind(); 259 260 /** 261 * Registers Signature as the constructor signature to use to inject a type. 262 * 263 * Example usage: 264 * 265 * fruit::createComponent() 266 * .registerConstructor<Foo(Bar*,Baz*)>() // Registers the constructor Foo::Foo(Bar*,Baz*) 267 * 268 * It's usually more convenient to use an INJECT macro or Inject typedef instead, e.g.: 269 * 270 * class Foo { 271 * public: 272 * // This also declares the constructor 273 * INJECT(Foo(Bar* bar, Baz* baz)); 274 * ... 275 * }; 276 * 277 * or (equivalent): 278 * 279 * class Foo { 280 * public: 281 * using Inject = Foo(Bar*, Baz*); 282 * Foo(Bar* bar, Baz* baz); 283 * ... 284 * }; 285 * 286 * Use registerConstructor() when you want to inject the class C in different ways in different components (just make 287 * sure those don't end up in the same injector, or use annotated injection to prevent the bindings from clashing), 288 * or when C is a third-party class that can't be modified. 289 * 290 * This supports annotated injection, just wrap the desired types (return type and/or argument types of the signature) 291 * with fruit::Annotated<> if desired. For example: 292 * 293 * struct Annotation1 {}; 294 * struct Annotation2 {}; 295 * 296 * struct Foo { 297 * Foo(Bar* bar) {...} 298 * }; 299 * 300 * fruit::Component<fruit::Annotated<Annotation1, Bar>> getBarComponent() {...} 301 * 302 * fruit::Component<fruit::Annotated<Annotation2, Foo>> getFooComponent() { 303 * return fruit::createComponent() 304 * .install(getBarComponent) 305 * .registerConstructor<fruit::Annotated<Annotation2, Foo>(fruit::Annotated<Annotation1, Bar*>)>(); 306 * } 307 * 308 * This does *not* support assisted injection, for that you should use registerFactory() instead. 309 * 310 * The allowed argument types in the signature are, for any class (or fundamental) type C: 311 * 312 * C 313 * C* 314 * C& 315 * const C* 316 * const C& 317 * shared_ptr<C> 318 * Provider<C> 319 * Provider<const C> 320 * Annotated<Annotation, C> (for any type `Annotation') 321 * Annotated<Annotation, C*> (for any type `Annotation') 322 * Annotated<Annotation, C&> (for any type `Annotation') 323 * Annotated<Annotation, const C*> (for any type `Annotation') 324 * Annotated<Annotation, const C&> (for any type `Annotation') 325 * Annotated<Annotation, shared_ptr<C>> (for any type `Annotation') 326 * Annotated<Annotation, Provider<C>> (for any type `Annotation') 327 * Annotated<Annotation, Provider<const C>> (for any type `Annotation') 328 */ 329 template <typename Signature> 330 PartialComponent<fruit::impl::RegisterConstructor<Signature>, Bindings...> registerConstructor(); 331 332 /** 333 * Use this method to bind the type C to a specific instance. 334 * The caller must ensure that the provided reference is valid for the entire lifetime of the component and of any 335 * components or injectors that install this component; the caller must also ensure that the object is destroyed after 336 * the last components/injectors using it are destroyed. 337 * 338 * Example usage: 339 * 340 * Component<Request> getRequestComponent(Request* request) { 341 * return fruit::createComponent() 342 * .bindInstance(*request); 343 * } 344 * 345 * NormalizedComponent<...> normalizedComponent = ...; 346 * Request request; 347 * Injector<...> injector(normalizedComponent, 348 * getRequestComponent, 349 * request)); 350 * 351 * This should be used sparingly (you should let Fruit handle the object lifetime when possible), but in some cases it 352 * is necessary; for example, if a web server creates an injector to handle each request, this method can be used to 353 * inject the request itself as in the example above (see the Server page in the Fruit tutorial for more details). 354 * 355 * It's also possible to bind constants, see the documentation of the bindInstance() method taking a const& for 356 * details. 357 */ 358 template <typename C> 359 PartialComponent<fruit::impl::BindInstance<C, C>, Bindings...> bindInstance(C& instance); 360 361 /** 362 * Similar to the previous, but binds a const&. Note that the reference must still outlive the component/injector 363 * as in the non-const case. 364 * When using this method, you must declare that the type is constant in the Component type. For example: 365 * 366 * Component<const MyExpensiveClass> getMyExpensiveClassComponent() { 367 * static const MyExpensiveClass my_expensive_class = createMyExpensiveClass(); 368 * return fruit::createComponent() 369 * .bindInstance(my_expensive_class); 370 * } 371 * 372 * Constant bindings can be used as other bindings, except that you can only inject the constant type (e.g. as a 373 * constructor parameter) as: 374 * 375 * C 376 * const C* 377 * const C& 378 * Provider<const C> 379 * Annotated<Annotation, C> (for any type `Annotation') 380 * Annotated<Annotation, const C*> (for any type `Annotation') 381 * Annotated<Annotation, const C&> (for any type `Annotation') 382 * Annotated<Annotation, Provider<const C>> (for any type `Annotation') 383 * 384 * While you can't inject it as: 385 * 386 * C* 387 * C& 388 * shared_ptr<C> 389 * Provider<C> 390 * Annotated<Annotation, C*> (for any type `Annotation') 391 * Annotated<Annotation, C&> (for any type `Annotation') 392 * Annotated<Annotation, shared_ptr<C>> (for any type `Annotation') 393 * Annotated<Annotation, Provider<C>> (for any type `Annotation') 394 */ 395 template <typename C> 396 PartialComponent<fruit::impl::BindConstInstance<C, C>, Bindings...> bindInstance(const C& instance); 397 398 /** 399 * This is deleted to catch cases where the instance would likely be destroyed before the component/injectors. 400 */ 401 template <typename C> 402 PartialComponent<fruit::impl::BindConstInstance<C, C>, Bindings...> bindInstance(C&&) = delete; 403 404 /** 405 * Similar to the first version of bindInstance(), but allows to specify an annotated type that 406 * will be bound to the specified value. 407 * For example, to bind an instance to the type fruit::Annotated<Hostname, std::string>, you can use: 408 * 409 * fruit::Component<fruit::Annotated<Hostname, std::string>> getHostnameComponent(std::string* hostname) { 410 * fruit::createComponent() 411 * .bindInstance<fruit::Annotated<Hostname, std::string>>(*hostname); 412 * } 413 */ 414 template <typename AnnotatedType, typename C> 415 PartialComponent<fruit::impl::BindInstance<AnnotatedType, C>, Bindings...> bindInstance(C& instance); 416 417 /** 418 * Similar to the previous, but binds a const&. Example usage: 419 * 420 * fruit::Component<fruit::Annotated<Hostname, const std::string>> getHostnameComponent() { 421 * static const std::string hostname = determineHostname(); 422 * fruit::createComponent() 423 * .bindInstance<fruit::Annotated<Hostname, std::string>>(hostname); 424 * } 425 * 426 * See the documentation for the bindInstance() overload that takes a non-annotated const& for more details. 427 */ 428 template <typename AnnotatedType, typename C> 429 PartialComponent<fruit::impl::BindConstInstance<AnnotatedType, C>, Bindings...> bindInstance(const C& instance); 430 431 /** 432 * This is deleted to catch cases where the instance would likely be destroyed before the component/injectors. 433 */ 434 template <typename AnnotatedType, typename C> 435 PartialComponent<fruit::impl::BindConstInstance<AnnotatedType, C>, Bindings...> bindInstance(C&& instance); 436 437 /** 438 * Registers `provider' as a provider of C, where provider is a lambda with no captures returning either C or C* 439 * (prefer returning a C by value instead of allocating a C using `new C', to avoid the allocation). 440 * 441 * When injecting a C, the arguments of the provider will be injected and the provider will then be called to create 442 * the C instance, that will then be stored in the injector. 443 * 444 * If `provider' returns a pointer, it must be non-null; otherwise the program will abort. 445 * 446 * Example: 447 * 448 * fruit::Component<Foo> getFooComponent() { 449 * return fruit::createComponent() 450 * .install(getBarComponent) 451 * .install(getBazComponent) 452 * .registerProvider([](Bar* bar, Baz* baz) { 453 * Foo foo(bar, baz); 454 * foo.initialize(); 455 * return foo; 456 * }); 457 * } 458 * 459 * As in the previous example, it's not necessary to specify the type parameter, it will be inferred by the compiler. 460 * 461 * registerProvider() can't be called with a plain function, but you can write a lambda that wraps the function to 462 * achieve the same result. 463 * 464 * Registering stateful functors (including lambdas with captures) is NOT supported. 465 * However, you can write something like: 466 * 467 * struct Functor { 468 * Functor(int n) {...} 469 * MyClass operator()(Foo* foo) const {...} 470 * }; 471 * 472 * Component<MyClass> getMyClassComponent() { 473 * static const Functor aFunctor(42); 474 * return fruit::createComponent() 475 * .install(getFooComponent) 476 * .bindInstance(aFunctor) 477 * .registerProvider([](const Functor& functor, Foo* foo) { return functor(foo); }); 478 * } 479 */ 480 template <typename Lambda> 481 PartialComponent<fruit::impl::RegisterProvider<Lambda>, Bindings...> registerProvider(Lambda lambda); 482 483 /** 484 * Similar to the previous version of registerProvider(), but allows to specify an annotated type 485 * for the provider. This allows to inject annotated types in the parameters and/or bind the 486 * provider to an annotated type. For example: 487 * 488 * struct MyAnnotation1 {}; 489 * struct MyAnnotation2 {}; 490 * 491 * Component<fruit::Annotated<Annotation1, Bar>> getBarComponent() {...} 492 * Component<Baz> getBazComponent() {...} 493 * 494 * fruit::Component<fruit::Annotated<Annotation2, Foo>> getFooComponent() { 495 * return fruit::createComponent() 496 * .install(getBarComponent) 497 * .install(getBazComponent) 498 * .registerProvider< 499 * fruit::Annotated<Annotation2, Foo>( 500 * fruit::Annotated<Annotation1, Bar*>, 501 * Baz*) 502 * >([](Bar* bar, Baz* baz) { 503 * Foo foo(bar, baz); 504 * foo.initialize(); 505 * return foo; 506 * }); 507 * } 508 */ 509 template <typename AnnotatedSignature, typename Lambda> 510 PartialComponent<fruit::impl::RegisterProvider<AnnotatedSignature, Lambda>, Bindings...> 511 registerProvider(Lambda lambda); 512 513 /** 514 * Similar to bind<I, C>(), but adds a multibinding instead. 515 * 516 * Multibindings are independent from bindings; creating a binding with bind doesn't count as a multibinding, and 517 * adding a multibinding doesn't allow to inject the type (it only allows to retrieve multibindings through the 518 * getMultibindings method of the injector). 519 * 520 * Unlike bindings, where adding a the same binding twice is allowed (and ignored), adding the same multibinding 521 * multiple times will result in the creation of multiple "equivalent" instances, that will all be returned by 522 * getMultibindings(). 523 * 524 * Another difference compared with normal bindings is that this can't be used to bind a 525 * std::function<std::unique_ptr<I>(Args...)> to a std::function<std::unique_ptr<C>(Args...)> or a 526 * std::function<C(Args...)>. 527 * 528 * As bind(), this supports annotated injection, just wrap I and/or C in fruit::Annotated<> if desired. See the 529 * documentation of bind() for more details. 530 */ 531 template <typename I, typename C> 532 PartialComponent<fruit::impl::AddMultibinding<I, C>, Bindings...> addMultibinding(); 533 534 /** 535 * Similar to bindInstance(), but adds a multibinding instead. 536 * 537 * Multibindings are independent from bindings; creating a binding with bindInstance doesn't count as a 538 * multibinding, and adding a multibinding doesn't allow to inject the type (it only allows to retrieve 539 * multibindings through the getMultibindings method of the injector). 540 * 541 * Unlike bindings, where adding a the same binding twice is allowed (and ignored), adding several multibindings for 542 * the same instance will result in duplicated values in the result of getMultibindings. 543 * 544 * Another difference compared to bindInstance() is that you can't use this to bind a const& (note that there is no 545 * overload of this method that takes a const&). 546 * 547 * This method adds a multibinding for C. If the object implements an interface I and you want to add a multibinding 548 * for that interface instead, you must cast the object to I& before passing it to this method. 549 * 550 * Note that this takes the instance by reference, not by value; it must remain valid for the entire lifetime of this 551 * component and of any injectors created from this component. 552 * 553 * Example use: 554 * 555 * class MyClass { 556 * ... 557 * }; 558 * 559 * fruit::Component<> getMyComponent() { 560 * static MyClass x = MyClass(...); 561 * static MyClass y = MyClass(...); 562 * return fruit::createComponent() 563 * .addInstanceMultibinding(x) 564 * .addInstanceMultibinding(y); 565 * } 566 * 567 * fruit::Injector<> injector(getMyComponent); 568 * // This vector contains {&x, &y}. 569 * const std::vector<MyClass*>& objects = injector.getMultibindings<MyClass>(); 570 */ 571 template <typename C> 572 PartialComponent<fruit::impl::AddInstanceMultibinding<C>, Bindings...> addInstanceMultibinding(C& instance); 573 574 /** 575 * Similar to the previous version of addInstanceMultibinding(), but allows to specify an 576 * annotated type. 577 * Example use: 578 * 579 * struct MyAnnotation {}; 580 * 581 * class MyClass { 582 * ... 583 * }; 584 * 585 * fruit::Component<> getMyComponent() { 586 * static MyClass x = MyClass(...); 587 * static MyClass y = MyClass(...); 588 * return fruit::createComponent() 589 * .addInstanceMultibinding<fruit::Annotated<MyAnnotation, MyClass>>(x) 590 * .addInstanceMultibinding<fruit::Annotated<MyAnnotation, MyClass>>(y); 591 * } 592 * 593 * fruit::Injector<> injector(getMyComponent); 594 * // This vector contains {&x, &y}. 595 * const std::vector<MyClass*>& objects = injector.getMultibindings<fruit::Annotated<MyAnnotation, MyClass>>(); 596 */ 597 template <typename AnnotatedC, typename C> 598 PartialComponent<fruit::impl::AddInstanceMultibinding<AnnotatedC>, Bindings...> addInstanceMultibinding(C& instance); 599 600 /** 601 * Equivalent to calling addInstanceMultibinding() for each elements of `instances'. 602 * See the documentation of addInstanceMultibinding() for more details. 603 * 604 * Note that this takes the vector by reference, not by value; the vector (and its elements) must remain valid for the 605 * entire lifetime of this component and of any injectors created from this component. 606 * 607 * Example use: 608 * 609 * class MyClass { 610 * ... 611 * }; 612 * 613 * fruit::Component<> getMyComponent() { 614 * static MyClass x = MyClass(...); 615 * static std::vector<MyClass> other_objects{MyClass(...), MyClass(...)}; 616 * return fruit::createComponent() 617 * .addInstanceMultibinding(x) 618 * .addInstanceMultibindings(other_objects); 619 * } 620 * 621 * fruit::Injector<> injector(getMyComponent); 622 * // This vector contains {&x, &(other_objects[0]), &(other_objects[1])}. 623 * const std::vector<MyClass*>& objects = injector.getMultibindings<MyClass>(); 624 */ 625 template <typename C> 626 PartialComponent<fruit::impl::AddInstanceVectorMultibindings<C>, Bindings...> 627 addInstanceMultibindings(std::vector<C>& instances); 628 629 /** 630 * Similar to the previous version of addInstanceMultibindings(), but it allows to specify an annotated type. 631 * 632 * Example use: 633 * 634 * class MyClass { 635 * ... 636 * }; 637 * 638 * fruit::Component<> getMyComponent() { 639 * static MyClass x = MyClass(...); 640 * static std::vector<MyClass> other_objects{MyClass(...), MyClass(...)}; 641 * return fruit::createComponent() 642 * .addInstanceMultibinding<fruit::Annotated<MyAnnotation, MyClass>>(x) 643 * .addInstanceMultibindings<fruit::Annotated<MyAnnotation, MyClass>>(other_objects); 644 * } 645 * 646 * fruit::Injector<> injector(getMyComponent); 647 * // This vector contains {&x, &(other_objects[0]), &(other_objects[1])}. 648 * const std::vector<MyClass*>& objects = injector.getMultibindings<fruit::Annotated<MyAnnotation, MyClass>>(); 649 */ 650 template <typename AnnotatedC, typename C> 651 PartialComponent<fruit::impl::AddInstanceVectorMultibindings<AnnotatedC>, Bindings...> 652 addInstanceMultibindings(std::vector<C>& instances); 653 654 /** 655 * Similar to registerProvider, but adds a multibinding instead. 656 * 657 * Multibindings are independent from bindings; creating a binding with registerProvider doesn't count as a 658 * multibinding, and adding a multibinding doesn't allow to inject the type (it only allows to retrieve multibindings 659 * through the getMultibindings method of the injector). 660 * 661 * Unlike bindings, where adding a the same binding twice is allowed (and ignored), adding the same multibinding 662 * provider multiple times will result in the creation of multiple "equivalent" instances, that will all be returned 663 * by getMultibindings. 664 * It is good practice to add the multibindings in a component that is "close" to the injector in the get*Component 665 * call chain, to avoid adding the same multibinding more than once. 666 * 667 * Example use: 668 * 669 * class MyClass { 670 * public: 671 * MyClass(int n) {...} 672 * }; 673 * 674 * fruit::Component<> getMyComponent() { 675 * return fruit::createComponent() 676 * .addMultibindingProvider([]() { return MyClass(10); }) 677 * .addMultibindingProvider([]() { return MyClass(10); }) 678 * .addMultibindingProvider([]() { return MyClass(20); }); 679 * } 680 * 681 * fruit::Injector<> injector(getMyComponent); 682 * // This vector contains {&x, &y, &z} where x and y are MyClass objects constructed with 10 and z is a MyClass 683 * // object constructed with 20. 684 * const std::vector<MyClass*>& objects = injector.getMultibindings<MyClass>(); 685 * 686 * Note that this method adds a multibinding for the type returned by the provider. If the returned object implements 687 * an interface I and you want to add a multibinding for that interface instead, you should cast the pointer to I* 688 * before returning it. 689 */ 690 template <typename Lambda> 691 PartialComponent<fruit::impl::AddMultibindingProvider<Lambda>, Bindings...> addMultibindingProvider(Lambda lambda); 692 693 /** 694 * Similar to the previous version of addMultibindingProvider(), but allows to specify an annotated type 695 * for the provider. This allows to inject annotated types in the parameters and/or bind the 696 * provider to an annotated type. 697 * 698 * Example use: 699 * 700 * struct MyAnnotation1 {}; 701 * struct MyAnnotation2 {}; 702 * 703 * Component<fruit::Annotated<Annotation1, Bar>> getBarComponent() {...} 704 * Component<Baz> getBazComponent() {...} 705 * 706 * fruit::Component<> getFooComponent() { 707 * return fruit::createComponent() 708 * .install(getBarComponent) 709 * .install(getBazComponent) 710 * .registerMultibindingProvider< 711 * fruit::Annotated<Annotation2, Foo>( 712 * fruit::Annotated<Annotation1, Bar*>, 713 * Baz*) 714 * >([](Bar* bar, Baz* baz) { 715 * Foo foo(bar, baz); 716 * foo.initialize(); 717 * return foo; 718 * }); 719 * } 720 * 721 * 722 * fruit::Injector<> injector(getFooComponent); 723 * // This vector contains {&x} where x is an instance of Foo constructed using the lambda above, with injected 724 * // instances of Bar and Baz. 725 * const std::vector<MyClass*>& objects = injector.getMultibindings<fruit::Annotated<Annotation2, Foo>>(); 726 */ 727 template <typename AnnotatedSignature, typename Lambda> 728 PartialComponent<fruit::impl::AddMultibindingProvider<AnnotatedSignature, Lambda>, Bindings...> 729 addMultibindingProvider(Lambda lambda); 730 731 /** 732 * Registers `factory' as a factory of C, where `factory' is a lambda with no captures returning C. 733 * This is typically used for assisted injection (but it can also be used if no parameters are assisted). 734 * 735 * C can be any class (or fundamental) type. If C is std::unique_ptr<T>, the factory together with a bind<I,C> in the 736 * same component will automatically bind the corresponding std::function that returns a std::unique_ptr<I>. 737 * See the documentation of bind() for more details. 738 * 739 * The returned type can't be a pointer type. If you don't want to return it by value, you should return a 740 * std::unique_ptr instead. 741 * 742 * Example: 743 * 744 * Component<std::function<std::unique_ptr<MyClass>(int)>> getMyClassComponent() { 745 * fruit::createComponent() 746 * .install(getFooComponent) 747 * .registerFactory<std::unique_ptr<MyClass>(Foo*, fruit::Assisted<int>)>( 748 * [](Foo* foo, int n) { 749 * return std::unique_ptr<MyClass>(new MyClass(foo, n)); 750 * }); 751 * } 752 * 753 * Injector<std::function<std::unique_ptr<MyClass>(int)>> injector(getMyClassComponent); 754 * 755 * std::function<std::unique_ptr<MyClass>(int)> factory(injector); 756 * std::unique_ptr<MyClass> x = factory(42); 757 * 758 * The parameters marked as Assisted will become parameters of the std::function (in the same order), while the others 759 * (e.g. Foo in the example above) will be injected. 760 * 761 * Unlike registerProvider(), where the signature is inferred, for this method the signature (including any Assisted 762 * annotations) must be specified explicitly, while the second template parameter is inferred. 763 * 764 * If the only thing that the factory does is to call new and the constructor of the class, it's usually more 765 * convenient to use an Inject typedef or INJECT macro instead, e.g. the following are equivalent to the above: 766 * 767 * class MyClass { 768 * public: 769 * using Inject = MyClass(Foo*, Assisted<int>); 770 * 771 * MyClass(Foo* foo, int n) {...} 772 * }; 773 * 774 * or: 775 * 776 * class MyClass { 777 * public: 778 * INJECT(MyClass(Foo* foo, ASSISTED(int) n)) {...} 779 * }; 780 * 781 * Use registerFactory() when you want to inject the class in different ways in different components (just make sure 782 * those don't end up in the same injector), or when MyClass is a third-party class that can't be modified. 783 * 784 * registerFactory() can't be called with a plain function, but you can write a lambda that wraps the function to 785 * achieve the same result. 786 * 787 * Registering stateful functors (including lambdas with captures) is NOT supported. 788 * However, you can write something like: 789 * 790 * struct Functor { 791 * Functor(float x) {...} 792 * std::unique_ptr<MyClass> operator()(Foo* foo, int n) {...} 793 * }; 794 * 795 * Component<std::function<std::unique_ptr<MyClass>(int)>> getMyClassComponent() { 796 * static const Functor aFunctor(42.0); 797 * return fruit::createComponent() 798 * ... // Bind Foo 799 * .bindInstance(aFunctor) 800 * .registerFactory< 801 * std::unique_ptr<MyClass>( 802 * Functor functor, 803 * Foo*, 804 * Assisted<int>) 805 * >([](Functor functor, Foo* foo, int n) { 806 * return functor(foo, n); 807 * }); 808 * } 809 */ 810 template <typename DecoratedSignature, typename Factory> 811 PartialComponent<fruit::impl::RegisterFactory<DecoratedSignature, Factory>, Bindings...> 812 registerFactory(Factory factory); 813 814 /** 815 * Adds the bindings (and multibindings) in the Component obtained by calling fun(args...) to the current component. 816 * 817 * For example, these component functions: 818 * fruit::Component<Foo> getComponent1(); 819 * fruit::Component<Bar> getComponent2(int n, std::string s); 820 * 821 * can be combined as: 822 * 823 * fruit::Component<Foo, Bar> getFooBarComponent() { 824 * return fruit::createComponent() 825 * .install(getComponent1) 826 * .install(getComponent2, 5, std::string("Hello")); 827 * } 828 * 829 * If any `args` are provided, they must be: 830 * - Copy-constructible 831 * - Move-constructible 832 * - Assignable 833 * - Move-assignable 834 * - Equality comparable (i.e., operator== must be defined for two values of that type) 835 * - Hashable (i.e., std::hash must be defined for values of that type) 836 * 837 * Note that this only applies to `args`. E.g. in the example above `int` and `std::string` must satisfy this 838 * requirement (and they do), but `Foo` and `Bar` don't need to. 839 * 840 * Args and FormalArgs (if any) must be the same types; or to be precise, each type in Args must be convertible into 841 * the corresponding type in FormalArgs. 842 * 843 * A lambda with no captures can also be used as the first argument, for example: 844 * 845 * fruit::Component<Foo, Bar> getFooBarComponent() { 846 * return fruit::createComponent() 847 * .install([]() { return getComponent1(); }) 848 * .install([](int n) { return getComponent2(n, std::string("Hello")); }, 5); 849 * } 850 * 851 * These two install() calls are equivalent to the previous ones. 852 * 853 * As in the example, the template parameters for this method will be inferred by the compiler, it's not necessary to 854 * specify them explicitly. 855 * 856 * Fruit automatically de-duplicates install() calls, so they're effectively memoized (within each injector). 857 * For example, in this code: 858 * 859 * fruit::Component<Foo> getFooComponent() {...} 860 * 861 * fruit::Component<Bar> getBarComponent() { 862 * return fruit::createComponent() 863 * .install(getFooComponent) 864 * .bind<Bar, BarImpl>(); 865 * } 866 * 867 * fruit::Component<Baz> getBazComponent() { 868 * return fruit::createComponent() 869 * .install(getFooComponent) 870 * .bind<Baz, BazImpl>(); 871 * } 872 * 873 * fruit::Component<Bar, Baz> getBarBazComponent() { 874 * return fruit::createComponent() 875 * .install(getBarComponent) 876 * .install(getBazComponent); 877 * } 878 * 879 * fruit::Injector<Bar, Baz> injector(getBarBazComponent); 880 * 881 * 882 * getFooComponent() will only be called once. 883 * For Component functions with arguments, only one call will be done for each set of arguments, but multiple calls 884 * might be made if multiple sets of arguments are used. 885 * 886 * If you actually want a Component function to be called/installed multiple times (e.g. if it binds a multibinding 887 * and you actually want multiple multibindings to be bound) you can add a dummy argument and specify different values 888 * for that argument when installing the component. 889 */ 890 template <typename... OtherComponentParams, typename... FormalArgs, typename... Args> 891 PartialComponent<fruit::impl::InstallComponent<fruit::Component<OtherComponentParams...>(FormalArgs...)>, Bindings...> 892 install(fruit::Component<OtherComponentParams...> (*)(FormalArgs...), Args&&... args); 893 894 /** 895 * Similar to install(), but allows to install a variable number of component functions instead of just 1. This 896 * additional flexibility is sometimes useful in templated `get*Component` functions and for other advanced use-cases. 897 * 898 * To use this method, wrap each get*Component function with its args in a fruit::ComponentFunction<...> object (using 899 * the helper function fruit::componentFunction), then pass all the fruit::ComponentFunction<...> objects (which can 900 * potentially have different params) to this method. 901 * 902 * For example: 903 * 904 * fruit::Component<Foo, Bar> getBarBazComponent() { 905 * return fruit::createComponent() 906 * .installComponentFunctions( 907 * fruit::componentFunction(getFooComponent, a, b, c), 908 * fruit::componentFunction(getBarComponent, x, y)); 909 * } 910 * 911 * Is equivalent to: 912 * 913 * fruit::Component<Foo, Bar> getBarBazComponent() { 914 * return fruit::createComponent() 915 * .install(getFooComponent, a, b, c) 916 * .install(getBarComponent, x, y); 917 * } 918 * 919 * This is a simple example to show the idea, however in a simple case like this it's easier to just use install(). 920 */ 921 template <typename... ComponentFunctions> 922 PartialComponent<fruit::impl::InstallComponentFunctions<ComponentFunctions...>, Bindings...> 923 installComponentFunctions(ComponentFunctions... componentFunctions); 924 925 /** 926 * This class is returned by PartialComponent::replace, see the documentation of that method for more information. 927 */ 928 template <typename ReplacedComponent, typename... GetReplacedComponentFormalArgs> 929 class PartialComponentWithReplacementInProgress { 930 private: 931 using storage_t = fruit::impl::PartialComponentStorage< 932 fruit::impl::PartialReplaceComponent<ReplacedComponent(GetReplacedComponentFormalArgs...)>, Bindings...>; 933 934 public: 935 template <typename... FormalArgs, typename... Args> 936 PartialComponent<fruit::impl::ReplaceComponent<ReplacedComponent(GetReplacedComponentFormalArgs...), 937 ReplacedComponent(FormalArgs...)>, 938 Bindings...> 939 with(ReplacedComponent (*)(FormalArgs...), Args&&... args); 940 PartialComponentWithReplacementInProgress(storage_t storage)941 PartialComponentWithReplacementInProgress(storage_t storage) // NOLINT(google-explicit-constructor) 942 : storage(storage) {} 943 944 private: 945 storage_t storage; 946 947 PartialComponentWithReplacementInProgress() = delete; 948 }; 949 950 /** 951 * This allows to replace an installed Component with another one. This is useful for testing. 952 * For example, if you have these components: 953 * 954 * fruit::Component<MyDependency> getDependencyComponent() {...} 955 * 956 * fruit::Component<Foo> getFooComponent() { 957 * return fruit::createComponent() 958 * .install(getDependencyComponent) 959 * .bind<Foo, FooImpl>(); 960 * } 961 * 962 * fruit::Component<Bar> getBarComponent() { 963 * return fruit::createComponent() 964 * .install(getFooComponent) 965 * .bind<Bar, BarImpl>(); 966 * } 967 * 968 * When you test Bar, you might want to replace getDependencyComponent with a component that binds a fake 969 * MyDependency: 970 * 971 * fruit::Component<MyDependency> getFakeDependencyComponent() {...} 972 * 973 * To do so, you can define a component like: 974 * 975 * fruit::Component<Bar> getBarComponentWithFakeDependency() { 976 * return fruit::createComponent() 977 * .replace(getDependencyComponent).with(getFakeDependencyComponent) 978 * .install(getBarComponent); 979 * } 980 * 981 * This component is equivalent to: 982 * 983 * fruit::Component<Bar> getBarComponentWithFakeDependency() { 984 * return fruit::createComponent() 985 * .install(getFakeDependencyComponent) 986 * .bind<Foo, FooImpl>() 987 * .bind<Bar, BarImpl>(); 988 * } 989 * 990 * However this way you don't need to duplicate the bindings for Foo and Bar, and you don't even need to include them 991 * in the translation unit (i.e., cc/cpp file) that defines getBarComponentWithFakeDependency(). 992 * In codebases with many layers, this can save a lot of duplication. 993 * 994 * Note that the .replace(...).with(...) must appear *before* installing the component to which it's applied to; 995 * e.g., in the example above note how we install getBarComponent after the replacement in 996 * getBarComponentWithFakeDependency. 997 * If you add a replacement after the replaced component has been installed, Fruit will report an error at run-time. 998 * 999 * In the example above, the replaced and replacement component functions had no arguments, however it's also possible 1000 * to replace component functions with args. The arguments of the replaced and replacement component functions are 1001 * independent; for example .replace(getDependencyComponentWithArgs, 15).with(myFakeComponentWithNoArgs) is allowed 1002 * and it would replace all install(getDependencyComponentWithArgs, 15) calls with install(myFakeComponentWithNoArgs). 1003 * 1004 * The component types returned by the replaced and replacement components must be the same. For example, this is NOT 1005 * allowed: 1006 * 1007 * fruit::Component<MyDependency, SomethingElse> getFakeDependencyComponentWithSomethingElse() {...} 1008 * 1009 * fruit::Component<Bar> getBarComponentWithFakeDependency() { 1010 * return fruit::createComponent() 1011 * .replace(getDependencyComponent).with(getFakeDependencyComponentWithSomethingElse) // error! 1012 * .install(getBarComponent); 1013 * } 1014 * 1015 * But replacing a replaced component is allowed: 1016 * 1017 * fruit::Component<MyDependency> getOtherFakeDependencyComponent() {...} 1018 * 1019 * fruit::Component<Bar> getBarComponentWithOtherFakeDependency() { 1020 * return fruit::createComponent() 1021 * // The two replacements can appear in any order, but they must both be before the install(). 1022 * .replace(getFakeDependencyComponent).with(getOtherFakeDependencyComponent) 1023 * .replace(getDependencyComponent).with(getFakeDependencyComponent) 1024 * .install(getBarComponent); 1025 * } 1026 * 1027 * Of course this is a simple example, in the real world the replacements and the install would probably come from 1028 * other components. 1029 * 1030 * And note that you can also replace components that define replacements, for example: 1031 * 1032 * fruit::Component<> getFakeDependencyReplacementComponent() { 1033 * return fruit::createComponent() 1034 * .replace(getDependencyComponent).with(getFakeDependencyComponentWithSomethingElse); 1035 * } 1036 * 1037 * fruit::Component<...> getComponent() { 1038 * return fruit::createComponent() 1039 * .replace(getFakeDependencyReplacementComponent).with(...) 1040 * .install(...); 1041 * } 1042 * 1043 * Replacements are only installed if the replaced component is installed, otherwise they are ignored. 1044 * In the first example above, if getFooComponent didn't install getDependencyComponent, when a test creates an 1045 * injector for getBarComponentWithFakeDependency it would not install getFakeDependencyComponent. 1046 */ 1047 template <typename... OtherComponentParams, typename... FormalArgs, typename... Args> 1048 typename PartialComponent<Bindings...>::template PartialComponentWithReplacementInProgress< 1049 fruit::Component<OtherComponentParams...>, FormalArgs...> 1050 replace(fruit::Component<OtherComponentParams...> (*)(FormalArgs...), Args&&... args); 1051 1052 ~PartialComponent() = default; 1053 1054 // Do not use. Use fruit::createComponent() instead. 1055 PartialComponent() = delete; 1056 1057 // Do not use. Only use PartialComponent for temporaries, and then convert it to a Component. 1058 PartialComponent(const PartialComponent&) = delete; 1059 PartialComponent(PartialComponent&&) = delete; 1060 1061 private: 1062 template <typename... OtherBindings> 1063 friend class PartialComponent; 1064 1065 template <typename... Types> 1066 friend class Component; 1067 1068 fruit::impl::PartialComponentStorage<Bindings...> storage; 1069 1070 PartialComponent(fruit::impl::PartialComponentStorage<Bindings...> storage); // NOLINT(google-explicit-constructor) 1071 1072 template <typename NewBinding> 1073 using OpFor = typename fruit::impl::meta::OpForComponent<Bindings...>::template AddBinding<NewBinding>; 1074 1075 friend PartialComponent<> createComponent(); 1076 }; 1077 1078 } // namespace fruit 1079 1080 #include <fruit/impl/component.defn.h> 1081 1082 #endif // FRUIT_COMPONENT_H 1083