1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
//! Coi provides an easy to use dependency injection framework. //! Currently, this crate provides the following: //! - **[`coi::Inject` (trait)]** - a marker trait that indicates a trait or struct is injectable. //! - **[`coi::Provide`]** - a trait that indicates a struct is capable of providing a specific //! implementation of some injectable trait. This is generated for you if you use //! [`coi::Inject` (derive)], but can also be written manually. //! - **[`coi::Container`]** - a container to manage the lifetime of all dependencies. This is still //! in its early stages, and currently only supports objects that are recreated with each request to //! [`coi::Container::resolve`]. //! - **[`coi::ContainerBuilder`]** - a builder for the above container to simplify construction and //! guarantee immutability after construction. //! //! [`coi::Inject` (trait)]: trait.Inject.html //! [`coi::Inject` (derive)]: derive.Inject.html //! [`coi::Provide`]: trait.Provide.html //! [`coi::Container`]: struct.Container.html //! [`coi::Container::resolve`]: struct.Container.html#method.resolve //! [`coi::ContainerBuilder`]: struct.ContainerBuilder.html //! //! # How this crate works //! //! For any trait you wish to abstract over, have it inherit the `Inject` trait. For structs, impl //! `Inject` for that struct, e.g. //! ```rust //! # use coi::Inject; //! trait Trait1: Inject {} //! //! struct Struct1; //! //! impl Inject for Struct1 {} //! ``` //! //! Then, in order to register the injectable item with the [`coi::ContainerBuilder`], you also //! need a struct that impls `Provide<Output = T>` where `T` is your trait or struct. `Provide` //! exposes a `provide` fn that takes `&self` and `&Container`. When manually implementing `Provide` //! you must resolve all dependencies with `container`. Here's an example below: //! //! ```rust //! # #[cfg(any(feature = "async", feature = "derive-async"))] { //! # use async_trait::async_trait; //! # use coi::{Container, Inject, Provide}; //! # use std::sync::Arc; //! # trait Trait1: Inject {} //! # //! trait Dependency: Inject {} //! //! struct Impl1 { //! dependency: Arc<dyn Dependency>, //! } //! //! impl Impl1 { //! fn new(dependency: Arc<dyn Dependency>) -> Self { //! Self { dependency } //! } //! } //! //! impl Inject for Impl1 {} //! //! impl Trait1 for Impl1 {} //! //! struct Trait1Provider; //! //! #[async_trait] //! impl Provide for Trait1Provider { //! type Output = dyn Trait1; //! //! async fn provide(&self, container: &mut Container) -> coi::Result<Arc<Self::Output>> { //! let dependency = container.resolve::<dyn Dependency>("dependency").await?; //! Ok(Arc::new(Impl1::new(dependency)) as Arc<dyn Trait1>) //! } //! } //! # } //! ``` //! //! The `"dependency"` above of course needs to be registered in order for the call //! to `resolve` to not error out: //! //! ```rust //! # #[cfg(any(feature = "async", feature="derive-async"))] { //! # use async_trait::async_trait; //! # use coi::{container, Container, Inject, Provide}; //! # use std::sync::Arc; //! # trait Trait1: Inject {} //! # trait Dependency: Inject {} //! # //! # struct Impl1 { //! # dependency: Arc<dyn Dependency>, //! # } //! # impl Impl1 { //! # fn new(dependency: Arc<dyn Dependency>) -> Self { //! # Self { dependency } //! # } //! # } //! # impl Inject for Impl1 {} //! # impl Trait1 for Impl1 {} //! # //! # struct Trait1Provider; //! # //! # #[async_trait] //! # impl Provide for Trait1Provider { //! # type Output = dyn Trait1; //! # async fn provide(&self, container: &mut Container) -> coi::Result<Arc<Self::Output>> { //! # let dependency = container.resolve::<dyn Dependency>("dependency").await?; //! # Ok(Arc::new(Impl1::new(dependency)) as Arc<dyn Trait1>) //! # } //! # } //! struct DepImpl; //! //! impl Dependency for DepImpl {} //! //! impl Inject for DepImpl {} //! //! struct DependencyProvider; //! //! #[async_trait] //! impl Provide for DependencyProvider { //! type Output = dyn Dependency; //! //! async fn provide(&self, _: &mut Container) -> coi::Result<Arc<Self::Output>> { //! Ok(Arc::new(DepImpl) as Arc<dyn Dependency>) //! } //! } //! //! async move { //! let mut container = container! { //! trait1 => Trait1Provider, //! dependency => DependencyProvider, //! }; //! let trait1 = container.resolve::<dyn Trait1>("trait1").await; //! }; //! # } //! ``` //! //! In general, you usually won't want to write all of that. You would instead want to use the //! procedural macro (see example below). //! The detailed docs for that are at [`coi::Inject` (derive)] //! //! # Example //! //! ```rust //! # #[cfg(feature = "derive-async")] { //! use coi::{container, Inject}; //! use std::sync::Arc; //! //! // Mark injectable traits by inheriting the `Inject` trait. //! trait Trait1: Inject { //! fn describe(&self) -> &'static str; //! } //! //! // For structs that will provide the implementation of an injectable trait, derive `Inject` //! // and specify which expr will be used to inject which trait. The method can be any path. //! // The arguments for the method are derived from fields marked with the attribute `#[inject]` //! // (See Impl2 below). //! #[derive(Inject)] //! // Currently, only one trait can be provided, but this will likely be expanded on in future //! // versions of this crate. //! #[provides(dyn Trait1 with Impl1)] //! struct Impl1; //! //! // Don't forget to actually implement the trait ;). //! impl Trait1 for Impl1 { //! fn describe(&self) -> &'static str { //! "I'm impl1!" //! } //! } //! //! // Mark injectable traits by inheriting the `Inject` trait. //! trait Trait2: Inject { //! fn deep_describe(&self) -> String; //! } //! //! // For structs that will provide the implementation of an injectable trait, derive `Inject` //! // and specify which method will be used to inject which trait. The arguments for the method //! // are derived from fields marked with the attribute `#[inject]`, so the parameter name must //! // match a field name. //! #[derive(Inject)] //! #[provides(dyn Trait2 with Impl2::new(trait1))] //! struct Impl2 { //! // The name of the field is important! It must match the name that's registered in the //! // container when the container is being built! This is similar to the behavior of //! // dependency injection libraries in other languages. //! #[inject] //! trait1: Arc<dyn Trait1>, //! } //! //! // Implement the provider method //! impl Impl2 { //! // Note: The param name here doesn't actually matter. //! fn new(trait1: Arc<dyn Trait1>) -> Self { //! Self { trait1 } //! } //! } //! //! // Again, don't forget to actually implement the trait ;). //! impl Trait2 for Impl2 { //! fn deep_describe(&self) -> String { //! format!("I'm impl2! and I have {}", self.trait1.describe()) //! } //! } //! //! // You might note that Container::resolve is async. This is to allow any provider to be async //! // and since we don't know from the resolution perspective whether any provider will need to be //! // async, they all have to be. This might be configurable through feature flags in a future //! // version of the library. //! async move { //! // "Provider" structs are automatically generated through the `Inject` attribute. They //! // append `Provider` to the name of the struct that is being derive (make sure you don't //! // any structs with the same name or your code will fail to compile. //! // Reminder: Make sure you use the same key here as the field names of the structs that //! // require these impls. //! let mut container = container! { //! trait1 => Impl1Provider, //! trait2 => Impl2Provider, //! }; //! //! // Once the container is built, you can now resolve any particular instance by its key and //! // the trait it provides. This crate currently only supports `Arc<dyn Trait>`, but this may //! // be expanded in a future version of the crate. //! let trait2 = container //! // Note: Getting the key wrong will produce an error telling you which key in the //! // chain of dependencies caused the failure (future versions might provider a vec of //! // chain that lead to the failure). Getting the type wrong will only tell you which key //! // had the wrong type. This is because at runtime, we do not have any type information, //! // only unique ids (that change during each compilation). //! .resolve::<dyn Trait2>("trait2") //! .await //! .expect("Should exist"); //! println!("Deep description: {}", trait2.deep_describe()); //! }; //! # } //! ``` //! //! # Features //! //! Compilation taking too long? Turn off features you're not using. //! //! To not use the default, and e.g. only the "async" feature: //! ```toml //! # Cargo.toml //! [dependencies] //! coi = { version = "...", default-features = false, features = ["async"] } //! ``` //! //! - default: `derive-async` - Procedural macros are re-exported, async is available. //! - `derive` - Procedural macros are re-exported, but none of the code provides async support. //! - `async` - Procedural macros are not re-exported, so all generated code must be written //! manually. Async support is available. //! - None - Procedural macros are not re-exported and none of the code is async //! //! # Help //! //! ## External traits //! //! Want to inject a trait that's not marked `Inject`? There's a very simple solution! //! It works even if the intended trait is not part of your crate. //! ```rust //! # use coi::Inject; //! // other.rs //! pub trait Trait { //! # /* //! ... //! # */ //! } //! //! // your_lib.rs //! # /* //! use coi::Inject; //! use other::Trait; //! # */ //! //! // Just inherit the intended trait and `Inject` on a trait in your crate, //! // and make sure to also impl both traits for the intended provider. //! pub trait InjectableTrait : Trait + Inject {} //! //! #[derive(Inject)] //! #[provides(pub dyn InjectableTrait with Impl{})] //! struct Impl { //! # /* //! ... //! # */ //! } //! //! impl Trait for Impl { //! # /* //! ... //! # */ //! } //! //! impl InjectableTrait for Impl {} //! ``` //! //! ## Where are the factory registrations!? //! //! If you're familiar with dependency injection in other languages, you might //! be used to factory registration where you can provide a method/closure/lambda/etc. //! during registration. Since the crate works off of the `Provide` trait, you would //! have to manually implement `Provide` for your factory method. This would also //! require you to manually retrieve your dependencies from the passed in `Container` //! as shown in the docs above. //! //! ## Why can't I derive `Inject` when my struct contains a reference? //! //! In order to store all of the resolved types, we have to use //! [`std::any::Any`], which, unfortunately, has the restriction `Any: 'static`. //! This is because it's not yet known if there's a safe way to downcast to a //! type with a reference (See the comments in this [tracking issue]). //! //! [`std::any::Any`]: https://doc.rust-lang.org/std/any/trait.Any.html //! [tracking issue]: https://github.com/rust-lang/rust/issues/41875 use std::any::Any; use std::collections::HashMap; use std::fmt::{self, Display}; use std::sync::Arc; #[cfg(any(feature = "derive", feature = "derive-async"))] pub use coi_derive::*; /// A re-export of the `async_trait` attribute from the `async-trait` crate. See [`async-trait`]. /// /// [`async-trait`]: https://docs.rs/async-trait #[cfg(feature = "async")] pub use async_trait::async_trait; #[cfg(feature = "async")] use futures::future::{BoxFuture, FutureExt}; #[cfg(feature = "async")] type Mutex<T> = async_std::sync::Mutex<T>; #[cfg(not(feature = "async"))] type Mutex<T> = std::sync::Mutex<T>; /// Errors produced by this crate #[derive(Debug)] pub enum Error { /// This key was not found in the container. Either the requested resource was never registered /// with this container, or there is a typo in the register or resolve calls. KeyNotFound(String), /// The requested key was found in the container, but its type did not match the requested type. TypeMismatch(String), /// Wrapper around errors produced by `Provider`s. Inner(Box<dyn std::error::Error + Send + Sync + 'static>), } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::result::Result<(), fmt::Error> { match self { Error::KeyNotFound(s) => write!(f, "Key not found: {}", s), Error::TypeMismatch(s) => write!(f, "Type mismatch for key: {}", s), Error::Inner(ptr) => write!(f, "Inner error: {}", ptr), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::KeyNotFound(_) | Error::TypeMismatch(_) => None, Error::Inner(ptr) => Some(ptr.as_ref()), } } } /// Type alias to `Result<T, coi::Error>`. pub type Result<T> = std::result::Result<T, Error>; /// A marker trait for injectable traits and structs. pub trait Inject: Send + Sync + 'static {} impl<T: Inject + ?Sized> Inject for Arc<T> {} /// Control when `Container` will call `Provide::provide`. #[derive(Clone)] pub enum Registration<T> { /// `Container` will construct a new instance of `T` for every invocation /// of `Container::resolve`. /// /// # Example /// ```rust /// # use async_std::task; /// # use coi::{container, Inject, Result}; /// # use std::ops::Deref; /// # trait Trait: Inject {} /// # #[derive(Inject)] /// # #[provides(dyn Trait with Impl)] /// # struct Impl; /// # impl Trait for Impl {} /// # async fn the_test() -> Result<()> { /// let mut container = container! { /// // same as trait => ImplProvider.normal /// trait => ImplProvider /// }; /// /// let instance_1 = container.resolve::<dyn Trait>("trait").await?; /// let instance_2 = container.resolve::<dyn Trait>("trait").await?; /// /// // Every instance resolved from the container will be a distinct instance. /// assert_ne!( /// instance_1.deref() as &dyn Trait as *const _, /// instance_2.deref() as &dyn Trait as *const _ /// ); /// # Ok(()) /// # } /// # task::block_on(async { /// # the_test().await.unwrap() /// # }); /// ``` Normal(T), /// `Container` will construct a new instance of `T` for each scope /// container created through `Container::scoped`. /// /// # Example /// ```rust /// # use async_std::task; /// # use coi::{container, Inject, Result}; /// # use std::ops::Deref; /// # trait Trait: Inject {} /// # #[derive(Inject)] /// # #[provides(dyn Trait with Impl)] /// # struct Impl; /// # impl Trait for Impl {} /// # async fn the_test() -> Result<()> { /// let mut container = container! { /// trait => ImplProvider.scoped /// }; /// /// // Every instance resolved within the same scope will be the same instance. /// let instance_1 = container.resolve::<dyn Trait>("trait").await?; /// let instance_2 = container.resolve::<dyn Trait>("trait").await?; /// assert_eq!( /// instance_1.deref() as &dyn Trait as *const _, /// instance_2.deref() as &dyn Trait as *const _ /// ); /// { /// let mut scoped = container.scopable().scoped().await; /// let instance_3 = scoped.resolve::<dyn Trait>("trait").await?; /// /// // Since these two were resolved in different scopes, they will never be the /// // same instance. /// assert_ne!( /// instance_1.deref() as &dyn Trait as *const _, /// instance_3.deref() as &dyn Trait as *const _ /// ); /// } /// # Ok(()) /// # } /// # task::block_on(async { /// # the_test().await.unwrap() /// # }); /// ``` Scoped(T), /// The container will construct a single instance of `T` and reuse it /// throughout all scopes. /// /// # Example /// ```rust /// # use async_std::task; /// # use coi::{container, Inject, Result}; /// # use std::ops::Deref; /// # trait Trait: Inject {} /// # #[derive(Inject)] /// # #[provides(dyn Trait with Impl)] /// # struct Impl; /// # impl Trait for Impl {} /// # async fn the_test() -> Result<()> { /// let mut container = container! { /// trait => ImplProvider.singleton /// }; /// /// let instance_1 = container.resolve::<dyn Trait>("trait").await?; /// let instance_2 = container.resolve::<dyn Trait>("trait").await?; /// /// assert_eq!( /// instance_1.deref() as &dyn Trait as *const _, /// instance_2.deref() as &dyn Trait as *const _ /// ); /// { /// let mut scoped = container.scopable().scoped().await; /// let instance_3 = scoped.resolve::<dyn Trait>("trait").await?; /// /// // Regardless of what scope the instance was resolved it, it will always /// // be the same instance. /// assert_eq!( /// instance_1.deref() as &dyn Trait as *const _, /// instance_3.deref() as &dyn Trait as *const _ /// ); /// } /// # Ok(()) /// # } /// # task::block_on(async { /// # the_test().await.unwrap() /// # }); /// ``` Singleton(T), } impl<T> Registration<T> { fn as_ref(&self) -> Registration<&T> { match self { Registration::Normal(t) => Registration::Normal(t), Registration::Scoped(t) => Registration::Scoped(t), Registration::Singleton(t) => Registration::Singleton(t), } } fn map<F, U>(self, func: F) -> Registration<U> where F: Fn(T) -> U, { match self { Registration::Normal(t) => Registration::Normal(func(t)), Registration::Scoped(t) => Registration::Scoped(func(t)), Registration::Singleton(t) => Registration::Singleton(func(t)), } } } /// A struct that manages all injected types. #[derive(Clone)] pub struct Container { provider_map: HashMap<String, Registration<Arc<dyn Any + Send + Sync>>>, resolved_map: HashMap<String, Arc<dyn Any + Send + Sync>>, parent: Option<Arc<Mutex<Container>>>, } macro_rules! lock { ($mutex:expr => await) => { $mutex.lock().await }; ($mutex:expr) => { $mutex.lock().unwrap() }; } macro_rules! resolve { (@result_ty $t:ty) => { Result<Arc<$t>> }; (@await $expr:expr, await) => { $expr.await }; (@await $expr:expr) => { $expr }; (@inner <$T:ty> $self:ident $key:ident $($await:ident)?) => { // If we already have a resolved version, return it. if $self.resolved_map.contains_key($key) { return $self .resolved_map .get($key) .unwrap() .downcast_ref::<Arc<$T>>() .map(Arc::clone) .ok_or_else(|| Error::TypeMismatch($key.to_owned())); } // Try to find the provider let any_provider = match $self.provider_map.get($key) { Some(provider) => provider, None => { // If the key is not found, then we might be a child container. If we have a // parent, then search it for a possibly valid provider. return match &$self.parent { Some(parent) => resolve!( @await lock!(parent $(=> $await)?).resolve::<$T>($key) $(, $await)? ), None => Err(Error::KeyNotFound($key.to_owned())), }; } }; let provider = any_provider.as_ref().map(|p| { p.downcast_ref::<Arc<dyn Provide<Output = $T> + Send + Sync + 'static>>() .map(Arc::clone) .ok_or_else(|| Error::TypeMismatch($key.to_owned())) }); match provider { Registration::Normal(p) => Ok(resolve!(@await p?.provide($self) $(, $await)?)?), Registration::Scoped(p) | Registration::Singleton(p) => { let provided = resolve!(@await p?.provide($self) $(, $await)?)?; $self.resolved_map.insert($key.to_owned(), Arc::new(provided)); Ok($self.resolved_map[$key] .downcast_ref::<Arc<$T>>() .map(Arc::clone) .unwrap()) } } }; (@async_wrapped $self:ident $key:ident) => { async move { resolve!(@inner $self $key await T) } }; (@def async) => { pub fn resolve<'a, 'b, 'c, T>( &'a mut self, key: &'b str ) -> BoxFuture<'c, resolve!(@result_ty T)> where 'a: 'c, 'b: 'c, T: Inject + ?Sized, { async move { resolve!{@inner <T> self key await} } .boxed() } }; (@def) => { pub fn resolve<T>(&mut self, key: &str) -> resolve!(@result_ty T) where T: Inject + ?Sized, { resolve!{ @inner <T> self key } } }; ($($async:ident)?) => { /// Construct or lookup a previously constructed object of type `T` with key `key`. resolve!{@def $($async)? } } } impl Container { #[cfg(feature = "async")] resolve! {async} #[cfg(not(feature = "async"))] resolve! {} /// Produce an object that can be converted into a scoped container. /// ```rust /// # #[cfg(any(feature = "async", feature = "derive-async"))] { /// # use coi::{container, Inject}; /// # trait Trait : Inject {} /// # #[derive(Inject)] /// # #[provides(dyn Trait with Impl)] /// # struct Impl; /// # impl Trait for Impl {} /// # async move { /// let mut container = container! { /// trait => ImplProvider.scoped /// }; /// let mut scoped_container = container.scopable().scoped().await; /// # }; /// # } /// ``` pub fn scopable(self) -> Scopable { Scopable(Arc::new(Mutex::new(self))) } } /// An intermediary struct used to construct a scoped container. See [`Container::scopable`] /// /// [`Container::scopable`]: struct.Container.html#method.scopable pub struct Scopable(Arc<Mutex<Container>>); macro_rules! scoped { (@fn $($async:ident $await:ident)?) => { /// Produce a child container that only contains providers for scoped registrations /// Any calls to resolve from the returned container can still use the `self` container /// to resolve any other kinds of registrations. pub $($async)? fn scoped(&self) -> Container { Container { provider_map: lock!(self.0 $(=> $await)?) .provider_map .iter() .filter_map(|(k, v)| match v { Registration::Scoped(v) => { Some((k.clone(), Registration::Scoped(Arc::clone(v)))) }, _ => None, }) .collect(), resolved_map: HashMap::new(), parent: Some(Arc::clone(&self.0)), } } }; (async) => { scoped!(@fn async await); }; () => { scoped!(@fn); } } impl Scopable { #[cfg(feature = "async")] scoped!(async); #[cfg(not(feature = "async"))] scoped!(); } /// A builder used to construct a `Container`. #[derive(Clone, Default)] pub struct ContainerBuilder { provider_map: HashMap<String, Registration<Arc<dyn Any + Send + Sync>>>, } impl ContainerBuilder { /// Constructor for `ContainerBuilder`. pub fn new() -> Self { Self { provider_map: HashMap::new(), } } /// Register a `Provider` for `T` with identifier `key`. #[inline] pub fn register<K, P, T>(self, key: K, provider: P) -> Self where K: Into<String>, T: Inject + ?Sized, P: Provide<Output = T> + Send + Sync + 'static, { self.register_as(key, Registration::Normal(provider)) } fn get_arc<P, T>(provider: P) -> Arc<dyn Provide<Output = T> + Send + Sync> where T: Inject + ?Sized, P: Provide<Output = T> + Send + Sync + 'static, { Arc::new(provider) } /// Register a `Provider` for `T` with identifier `key`, while also specifying the resolution /// behavior. pub fn register_as<K, P, T>(mut self, key: K, provider: Registration<P>) -> Self where K: Into<String>, T: Inject + ?Sized, P: Provide<Output = T> + Send + Sync + 'static, { let key = key.into(); self.provider_map.insert( key, provider.map(|p| Arc::new(Self::get_arc(p)) as Arc<dyn Any + Send + Sync>), ); self } /// Consume this builder to produce a `Container`. pub fn build(self) -> Container { Container { provider_map: self.provider_map, resolved_map: HashMap::new(), parent: None, } } } /// A trait to manage the construction of an injectable trait or struct. #[cfg(feature = "async")] #[async_trait] pub trait Provide { /// The type that this provider is intended to produce type Output: Inject + ?Sized; /// Only intended to be used internally async fn provide(&self, container: &mut Container) -> Result<Arc<Self::Output>>; } /// A trait to manage the construction of an injectable trait or struct. #[cfg(not(feature = "async"))] pub trait Provide { /// The type that this provider is intended to produce type Output: Inject + ?Sized; /// Only intended to be used internally fn provide(&self, container: &mut Container) -> Result<Arc<Self::Output>>; } #[cfg(test)] mod test { use super::*; #[test] fn ensure_display() { use std::io; let error = Error::KeyNotFound("S".to_owned()); let displayed = format!("{}", error); assert_eq!(displayed, "Key not found: S"); let error = Error::TypeMismatch("S2".to_owned()); let displayed = format!("{}", error); assert_eq!(displayed, "Type mismatch for key: S2"); let error = Error::Inner(Box::new(io::Error::new(io::ErrorKind::NotFound, "oh no!"))); let displayed = format!("{}", error); assert_eq!(displayed, "Inner error: oh no!"); } #[test] fn ensure_debug() { let error = Error::KeyNotFound("S".to_owned()); let debugged = format!("{:?}", error); assert_eq!(debugged, "KeyNotFound(\"S\")"); let error = Error::TypeMismatch("S2".to_owned()); let debugged = format!("{:?}", error); assert_eq!(debugged, "TypeMismatch(\"S2\")"); } #[test] fn conainer_builder_is_clonable() { let builder = ContainerBuilder::new(); for _ in 0..2 { let builder = builder.clone(); let _container = builder.build(); } } #[test] fn container_is_clonable() { let container = ContainerBuilder::new().build(); let _container = container.clone(); } } /// A macro to simplify building of `Container`s. /// /// It takes a list of key-value pairs, where the keys are converted to string /// keys, and the values are converted into registrations. Normal, singleton /// and scoped registrations are possible, with normal being the default: /// ```rust /// use coi::{container, Inject}; /// /// trait Dep: Inject {} /// /// #[derive(Inject)] /// #[provides(dyn Dep with Impl)] /// struct Impl; /// /// impl Dep for Impl {} /// /// let mut container = container! { /// dep => ImplProvider, /// normal_dep => ImplProvider.normal, /// singleton_dep => ImplProvider.singleton, /// scoped_dep => ImplProvider.scoped /// }; /// ``` /// /// For details on how each registration works, see [`coi::Registration`] /// /// [`coi::Registration`]: enum.Registration.html #[macro_export] macro_rules! container { (@registration $provider:ident scoped) => { ::coi::Registration::Scoped($provider) }; (@registration $provider:ident singleton) => { ::coi::Registration::Singleton($provider) }; (@registration $provider:ident normal) => { ::coi::Registration::Normal($provider) }; (@registration $provider:ident) => { ::coi::Registration::Normal($provider) }; (@line $builder:ident $key:ident $provider:ident $($call:ident)?) => { $builder = $builder.register_as(stringify!($key), container!(@registration $provider $($call)?)); }; ($($key:ident => $provider:ident $(. $call:ident)?),+) => { container!{ $( $key => $provider $(. $call)?, )+ } }; ($($key:ident => $provider:ident $(. $call:ident)?,)+) => { { let mut builder = ::coi::ContainerBuilder::new(); $(container!(@line builder $key $provider $($call)?);)+ builder.build() } } }