1use std::{
8 any::{Any, TypeId, type_name},
9 cell::RefCell,
10 collections::{HashMap, HashSet},
11 fmt,
12 sync::{Arc, Mutex, OnceLock},
13};
14
15pub use xmacros::*;
16
17pub mod middleware;
19pub use middleware::Application;
20
21pub mod guards;
23
24#[cfg(feature = "auth")]
26pub mod auth;
27
28#[cfg(feature = "upload")]
30pub mod upload;
31
32#[cfg(feature = "testing")]
34pub mod testing;
35
36#[cfg(feature = "cqrs")]
38pub mod cqrs;
39
40#[cfg(feature = "jobs")]
42pub mod jobs;
43
44#[cfg(feature = "cache")]
46pub mod cache;
47
48#[cfg(feature = "postgres")]
50pub mod database;
51
52pub mod config;
54
55mod lifecycle;
56
57mod scoped;
58pub use scoped::{Inject, with_container};
59
60pub mod exceptions;
62
63mod http;
64mod openapi;
65pub mod versioning;
67pub use http::{ApiOperation, ApiResponse, HttpError, HttpStatus, ValidatedJson, ValidatedQuery};
68pub use openapi::{DocumentationError, json_schema, openapi_document};
69pub use versioning::{ApiVersion, ApiVersions, VersionError};
70
71pub mod prelude {
73 pub use crate::{
74 Application, HttpError, HttpStatus, Inject, Injectable, controller, middleware, routes,
75 };
76 pub use axum::{
77 Json, Router,
78 response::{IntoResponse, Response},
79 };
80}
81
82type DynValue = dyn Any + Send + Sync;
83type Cache = Mutex<HashMap<ProviderKey, Arc<OnceLock<Result<Arc<DynValue>, InjectError>>>>>;
84type Factory = dyn Fn(&Container) -> Result<Arc<DynValue>, InjectError> + Send + Sync;
85
86#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
88pub enum Scope {
89 #[default]
90 Singleton,
92 Transient,
94 Request,
96}
97
98#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
100pub struct ProviderKey {
101 type_id: TypeId,
102 name: &'static str,
103}
104impl ProviderKey {
105 #[must_use]
106 pub fn of<T: 'static>() -> Self {
108 Self {
109 type_id: TypeId::of::<T>(),
110 name: type_name::<T>(),
111 }
112 }
113 #[must_use]
114 pub const fn name(self) -> &'static str {
116 self.name
117 }
118}
119
120#[derive(Debug, Clone, Eq, PartialEq)]
122pub enum InjectError {
123 Missing(&'static str),
125 DuplicateModule(&'static str),
127 DuplicateProvider(&'static str),
129 PrivateProviderAccess {
131 provider: &'static str,
133 module: &'static str,
135 },
136 InvalidExport {
138 provider: &'static str,
140 module: &'static str,
142 },
143 InvalidImport {
145 module: &'static str,
147 import: &'static str,
149 },
150 Circular(Vec<&'static str>),
152 InvalidScopeDependency {
154 owner: &'static str,
156 dependency: &'static str,
158 },
159 RequestScopeRequired(&'static str),
161 UndeclaredDependency {
163 owner: &'static str,
165 dependency: &'static str,
167 },
168 Downcast(&'static str),
170 ConstructionFailed(&'static str),
172 Poisoned,
174 AsyncInitializationRequired(&'static str),
176 InvalidLifecycleScope(&'static str),
178 LifecycleStopped,
180}
181impl fmt::Display for InjectError {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 match self {
184 Self::Missing(n) => write!(f, "missing provider: {n}"),
185 Self::DuplicateModule(n) => write!(f, "duplicate module: {n}"),
186 Self::DuplicateProvider(n) => write!(f, "duplicate provider: {n}"),
187 Self::PrivateProviderAccess { provider, module } => write!(
188 f,
189 "private provider {provider} is not visible to module {module}"
190 ),
191 Self::InvalidExport { provider, module } => write!(
192 f,
193 "module {module} exports unregistered provider {provider}"
194 ),
195 Self::InvalidImport { module, import } => {
196 write!(f, "module {module} imports unknown module {import}")
197 }
198 Self::Circular(chain) => write!(f, "circular dependency:\n{}", chain.join("\n -> ")),
199 Self::InvalidScopeDependency { owner, dependency } => write!(
200 f,
201 "invalid scope dependency: singleton {owner} depends on request-scoped {dependency}"
202 ),
203 Self::RequestScopeRequired(n) => write!(f, "request scope required for provider: {n}"),
204 Self::UndeclaredDependency { owner, dependency } => write!(
205 f,
206 "provider {owner} resolved undeclared dependency {dependency}"
207 ),
208 Self::Downcast(n) => write!(f, "provider {n} returned an incompatible value"),
209 Self::ConstructionFailed(reason) => write!(f, "provider construction failed: {reason}"),
210 Self::AsyncInitializationRequired(n) => {
211 write!(f, "provider {n} requires initialize_async")
212 }
213 Self::InvalidLifecycleScope(n) => {
214 write!(f, "lifecycle hooks require singleton scope: {n}")
215 }
216 Self::LifecycleStopped => write!(f, "container lifecycle stopped or interrupted"),
217 Self::Poisoned => write!(f, "container lock was poisoned"),
218 }
219 }
220}
221impl std::error::Error for InjectError {}
222
223pub struct ProviderDefinition {
225 key: ProviderKey,
226 scope: Scope,
227 dependencies: Vec<ProviderKey>,
228 optional_dependencies: Vec<ProviderKey>,
229 factory: Arc<Factory>,
230 async_factory: Option<Arc<lifecycle::AsyncFactory>>,
231 init_hook: Option<Arc<lifecycle::Hook>>,
232 shutdown_hook: Option<Arc<lifecycle::Hook>>,
233}
234impl fmt::Debug for ProviderDefinition {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 f.debug_struct("ProviderDefinition")
237 .field("key", &self.key)
238 .field("scope", &self.scope)
239 .field("dependencies", &self.dependencies)
240 .finish()
241 }
242}
243impl ProviderDefinition {
244 #[must_use]
245 pub fn new<T, F>(scope: Scope, dependencies: Vec<ProviderKey>, factory: F) -> Self
247 where
248 T: Send + Sync + 'static,
249 F: Fn(&Container) -> Result<T, InjectError> + Send + Sync + 'static,
250 {
251 Self {
252 key: ProviderKey::of::<T>(),
253 scope,
254 dependencies,
255 optional_dependencies: Vec::new(),
256 factory: Arc::new(move |c| factory(c).map(|v| Arc::new(v) as Arc<DynValue>)),
257 async_factory: None,
258 init_hook: None,
259 shutdown_hook: None,
260 }
261 }
262 #[must_use]
263 pub fn singleton<T, F>(dependencies: Vec<ProviderKey>, factory: F) -> Self
265 where
266 T: Send + Sync + 'static,
267 F: Fn(&Container) -> Result<T, InjectError> + Send + Sync + 'static,
268 {
269 Self::new(Scope::Singleton, dependencies, factory)
270 }
271 #[must_use]
272 pub fn request<T, F>(dependencies: Vec<ProviderKey>, factory: F) -> Self
274 where
275 T: Send + Sync + 'static,
276 F: Fn(&Container) -> Result<T, InjectError> + Send + Sync + 'static,
277 {
278 Self::new(Scope::Request, dependencies, factory)
279 }
280 #[must_use]
281 pub fn transient<T, F>(dependencies: Vec<ProviderKey>, factory: F) -> Self
283 where
284 T: Send + Sync + 'static,
285 F: Fn(&Container) -> Result<T, InjectError> + Send + Sync + 'static,
286 {
287 Self::new(Scope::Transient, dependencies, factory)
288 }
289 #[must_use]
290 pub fn value<T: Send + Sync + 'static>(value: T) -> Self {
292 let value: Arc<DynValue> = Arc::new(value);
293 Self {
294 key: ProviderKey::of::<T>(),
295 scope: Scope::Singleton,
296 dependencies: Vec::new(),
297 optional_dependencies: Vec::new(),
298 factory: Arc::new(move |_| Ok(value.clone())),
299 async_factory: None,
300 init_hook: None,
301 shutdown_hook: None,
302 }
303 }
304 #[must_use]
305 pub fn optional_dependency<T: 'static>(mut self) -> Self {
307 self.optional_dependencies.push(ProviderKey::of::<T>());
308 self
309 }
310 #[must_use]
311 pub fn key(&self) -> ProviderKey {
313 self.key
314 }
315 #[must_use]
316 pub fn scope(&self) -> Scope {
318 self.scope
319 }
320 #[must_use]
321 pub fn dependencies(&self) -> &[ProviderKey] {
323 &self.dependencies
324 }
325}
326
327pub trait Provider: Send + Sync + 'static {
329 fn scope() -> Scope {
331 Scope::Singleton
332 }
333 fn dependencies() -> Vec<ProviderKey> {
335 Vec::new()
336 }
337 fn optional_dependencies() -> Vec<ProviderKey> {
339 Vec::new()
340 }
341 fn provide(container: &Container) -> Result<Self, InjectError>
343 where
344 Self: Sized;
345 fn definition() -> ProviderDefinition
347 where
348 Self: Sized,
349 {
350 let mut definition =
351 ProviderDefinition::new(Self::scope(), Self::dependencies(), Self::provide);
352 definition.optional_dependencies = Self::optional_dependencies();
353 definition
354 }
355}
356
357#[derive(Clone, Default)]
359pub struct Container {
360 providers: Arc<HashMap<ProviderKey, ProviderDefinition>>,
361 singletons: Arc<Cache>,
362 request_values: Option<Arc<Cache>>,
363 lifecycle: Arc<lifecycle::Lifecycle>,
364 async_owner: Option<ProviderKey>,
365}
366
367thread_local! {
368 static RESOLVING: RefCell<Vec<(usize, ProviderKey)>> = const { RefCell::new(Vec::new()) };
369}
370struct ResolutionGuard;
371impl Drop for ResolutionGuard {
372 fn drop(&mut self) {
373 RESOLVING.with(|path| {
374 path.borrow_mut().pop();
375 });
376 }
377}
378impl Container {
379 #[must_use]
380 pub fn builder() -> ContainerBuilder {
382 ContainerBuilder::default()
383 }
384 pub fn resolve<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, InjectError> {
386 self.resolve_key(ProviderKey::of::<T>())?
387 .downcast::<T>()
388 .map_err(|_| InjectError::Downcast(type_name::<T>()))
389 }
390 pub fn resolve_optional<T: Send + Sync + 'static>(
392 &self,
393 ) -> Result<Option<Arc<T>>, InjectError> {
394 if !self.providers.contains_key(&ProviderKey::of::<T>()) {
395 return Ok(None);
396 }
397 self.resolve().map(Some)
398 }
399 fn resolve_key(&self, key: ProviderKey) -> Result<Arc<DynValue>, InjectError> {
400 let definition = self
401 .providers
402 .get(&key)
403 .ok_or(InjectError::Missing(key.name))?;
404 self.ensure_async_dependencies(key, &mut HashSet::new())?;
407 let identity = Arc::as_ptr(&self.providers) as usize;
408 RESOLVING.with(|path| {
409 let mut path = path.borrow_mut();
410 if !path.iter().any(|(id, _)| *id == identity)
411 && let Some(owner) = self.async_owner
412 && !self.providers[&owner].dependencies.contains(&key)
413 {
414 return Err(InjectError::UndeclaredDependency {
415 owner: owner.name,
416 dependency: key.name,
417 });
418 }
419 if let Some(index) = path.iter().position(|entry| *entry == (identity, key)) {
420 let mut chain = path[index..]
421 .iter()
422 .map(|entry| entry.1.name)
423 .collect::<Vec<_>>();
424 chain.push(key.name);
425 return Err(InjectError::Circular(chain));
426 }
427 if let Some((id, parent)) = path.last()
428 && *id == identity
429 && !self.providers[parent].dependencies.contains(&key)
430 {
431 return Err(InjectError::UndeclaredDependency {
432 owner: parent.name,
433 dependency: key.name,
434 });
435 }
436 path.push((identity, key));
437 Ok(())
438 })?;
439 let _guard = ResolutionGuard;
440 let cache = match definition.scope {
441 Scope::Transient => return (definition.factory)(self),
442 Scope::Singleton => &self.singletons,
443 Scope::Request => self
444 .request_values
445 .as_ref()
446 .ok_or(InjectError::RequestScopeRequired(key.name))?,
447 };
448 let slot = cache
450 .lock()
451 .map_err(|_| InjectError::Poisoned)?
452 .entry(key)
453 .or_default()
454 .clone();
455 if definition.async_factory.is_some() {
458 return slot
459 .get()
460 .cloned()
461 .unwrap_or(Err(InjectError::AsyncInitializationRequired(key.name)));
462 }
463 slot.get_or_init(|| {
464 if definition.scope == Scope::Singleton {
465 let root = Self {
467 providers: self.providers.clone(),
468 singletons: self.singletons.clone(),
469 request_values: None,
470 lifecycle: self.lifecycle.clone(),
471 async_owner: None,
472 };
473 (definition.factory)(&root)
474 } else {
475 (definition.factory)(self)
476 }
477 })
478 .clone()
479 }
480 #[must_use]
481 pub fn request(&self) -> RequestScope {
483 RequestScope {
484 container: Self {
485 providers: self.providers.clone(),
486 singletons: self.singletons.clone(),
487 request_values: Some(Arc::default()),
488 lifecycle: self.lifecycle.clone(),
489 async_owner: self.async_owner,
490 },
491 }
492 }
493 pub fn initialize(&self) -> Result<(), InjectError> {
496 if !self
497 .lifecycle
498 .ready
499 .load(std::sync::atomic::Ordering::Acquire)
500 && let Some(definition) = self.providers.values().find(|p| {
501 p.async_factory.is_some() || p.init_hook.is_some() || p.shutdown_hook.is_some()
502 })
503 {
504 return Err(InjectError::AsyncInitializationRequired(
505 definition.key.name,
506 ));
507 }
508 for definition in self
509 .providers
510 .values()
511 .filter(|definition| definition.scope == Scope::Singleton)
512 {
513 self.resolve_key(definition.key)?;
514 }
515 Ok(())
516 }
517}
518
519#[derive(Default)]
521pub struct ContainerBuilder {
522 providers: Vec<ProviderDefinition>,
523 overrides: Vec<ProviderDefinition>,
524}
525impl ContainerBuilder {
526 #[must_use]
527 pub fn provider(mut self, provider: ProviderDefinition) -> Self {
529 self.providers.push(provider);
530 self
531 }
532 #[must_use]
533 pub fn injectable<T: Provider>(self) -> Self {
535 self.provider(T::definition())
536 }
537 #[must_use]
539 pub fn override_provider(mut self, provider: ProviderDefinition) -> Self {
540 self.overrides.push(provider);
541 self
542 }
543 #[must_use]
545 pub fn value<T: Send + Sync + 'static>(self, value: T) -> Self {
546 self.provider(ProviderDefinition::value(value))
547 }
548 #[cfg(feature = "testing")]
549 pub(crate) fn into_definitions(self) -> Vec<ProviderDefinition> {
550 self.providers
551 }
552 pub fn build(self) -> Result<Container, InjectError> {
554 let mut providers = HashMap::new();
555 for provider in self.providers {
556 let key = provider.key;
557 if providers.insert(key, provider).is_some() {
558 return Err(InjectError::DuplicateProvider(key.name));
559 }
560 }
561 let mut overrides = HashSet::new();
562 for replacement in self.overrides {
563 let key = replacement.key;
564 if !overrides.insert(key) {
565 return Err(InjectError::DuplicateProvider(key.name));
566 }
567 if !providers.contains_key(&key) {
568 return Err(InjectError::Missing(key.name));
569 }
570 providers.insert(key, replacement);
571 }
572 for provider in providers.values() {
573 for dependency in &provider.dependencies {
574 if !providers.contains_key(dependency)
575 && !provider.optional_dependencies.contains(dependency)
576 {
577 return Err(InjectError::Missing(dependency.name));
578 }
579 }
580 }
581 for provider in providers.values() {
582 if provider.scope != Scope::Singleton
583 && (provider.init_hook.is_some() || provider.shutdown_hook.is_some())
584 {
585 return Err(InjectError::InvalidLifecycleScope(provider.key.name));
586 }
587 }
588 validate_provider_scopes(&providers)?;
589 validate_provider_cycles(&providers)?;
590 Ok(Container {
591 providers: Arc::new(providers),
592 singletons: Arc::default(),
593 request_values: None,
594 lifecycle: Arc::default(),
595 async_owner: None,
596 })
597 }
598}
599
600fn validate_provider_cycles(
601 providers: &HashMap<ProviderKey, ProviderDefinition>,
602) -> Result<(), InjectError> {
603 fn visit(
604 key: ProviderKey,
605 providers: &HashMap<ProviderKey, ProviderDefinition>,
606 visiting: &mut Vec<ProviderKey>,
607 visited: &mut HashSet<ProviderKey>,
608 ) -> Result<(), InjectError> {
609 if let Some(index) = visiting.iter().position(|entry| *entry == key) {
610 let mut chain = visiting[index..]
611 .iter()
612 .map(|entry| entry.name)
613 .collect::<Vec<_>>();
614 chain.push(key.name);
615 return Err(InjectError::Circular(chain));
616 }
617 if !visited.insert(key) {
618 return Ok(());
619 }
620 visiting.push(key);
621 if let Some(provider) = providers.get(&key) {
622 for dependency in &provider.dependencies {
623 if providers.contains_key(dependency) {
624 visit(*dependency, providers, visiting, visited)?;
625 }
626 }
627 }
628 visiting.pop();
629 Ok(())
630 }
631 let mut visiting = Vec::new();
632 let mut visited = HashSet::new();
633 for key in providers.keys().copied() {
634 visit(key, providers, &mut visiting, &mut visited)?;
635 }
636 Ok(())
637}
638fn validate_provider_scopes(
639 providers: &HashMap<ProviderKey, ProviderDefinition>,
640) -> Result<(), InjectError> {
641 for provider in providers
642 .values()
643 .filter(|provider| provider.scope == Scope::Singleton)
644 {
645 let mut pending = provider.dependencies.clone();
646 let mut visited = HashSet::new();
647 while let Some(key) = pending.pop() {
648 if !visited.insert(key) {
649 continue;
650 }
651 if let Some(dependency) = providers.get(&key) {
652 if dependency.scope == Scope::Request {
653 return Err(InjectError::InvalidScopeDependency {
654 owner: provider.key.name,
655 dependency: key.name,
656 });
657 }
658 pending.extend_from_slice(&dependency.dependencies);
659 }
660 }
661 }
662 Ok(())
663}
664
665#[derive(Clone)]
668pub struct RequestScope {
669 container: Container,
670}
671impl RequestScope {
672 pub(crate) fn belongs_to(&self, container: &Container) -> bool {
673 Arc::ptr_eq(&self.container.providers, &container.providers)
674 }
675 pub fn resolve<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, InjectError> {
677 self.container.resolve()
678 }
679 pub fn resolve_optional<T: Send + Sync + 'static>(
681 &self,
682 ) -> Result<Option<Arc<T>>, InjectError> {
683 self.container.resolve_optional()
684 }
685}
686
687pub type RequestContainer<'a> = RequestScope;
690
691#[derive(Debug)]
693pub struct ModuleDefinition {
694 pub name: &'static str,
696 pub providers: Vec<ProviderDefinition>,
698 pub imports: Vec<&'static str>,
700 pub exports: Vec<ProviderKey>,
702 pub global: bool,
704}
705impl ModuleDefinition {
706 #[must_use]
707 pub fn new(name: &'static str) -> Self {
709 Self {
710 name,
711 providers: Vec::new(),
712 imports: Vec::new(),
713 exports: Vec::new(),
714 global: false,
715 }
716 }
717 #[must_use]
718 pub fn provider(mut self, provider: ProviderDefinition) -> Self {
720 self.providers.push(provider);
721 self
722 }
723 #[must_use]
724 pub fn import(mut self, module: &'static str) -> Self {
726 self.imports.push(module);
727 self
728 }
729 #[must_use]
730 pub fn export<T: 'static>(mut self) -> Self {
732 self.exports.push(ProviderKey::of::<T>());
733 self
734 }
735 #[must_use]
736 pub fn global(mut self) -> Self {
738 self.global = true;
739 self
740 }
741}
742
743pub struct ModuleGraph {
745 modules: Vec<ModuleDefinition>,
746}
747impl ModuleGraph {
748 #[must_use]
749 pub fn new(modules: Vec<ModuleDefinition>) -> Self {
751 Self { modules }
752 }
753 pub fn build(self) -> Result<Container, InjectError> {
755 self.build_with_overrides(Vec::new())
756 }
757 pub fn build_with_overrides(
759 self,
760 overrides: Vec<ProviderDefinition>,
761 ) -> Result<Container, InjectError> {
762 let mut modules = HashMap::new();
763 for module in self.modules {
764 let name = module.name;
765 if modules.insert(name, module).is_some() {
766 return Err(InjectError::DuplicateModule(name));
767 }
768 }
769 for module in modules.values() {
770 let owned: HashSet<_> = module
771 .providers
772 .iter()
773 .map(ProviderDefinition::key)
774 .collect();
775 for export in &module.exports {
776 if !owned.contains(export) {
777 return Err(InjectError::InvalidExport {
778 provider: export.name,
779 module: module.name,
780 });
781 }
782 }
783 for import in &module.imports {
784 if !modules.contains_key(import) {
785 return Err(InjectError::InvalidImport {
786 module: module.name,
787 import,
788 });
789 }
790 }
791 }
792 for module in modules.values() {
793 let mut visible: HashSet<_> = module
794 .providers
795 .iter()
796 .map(ProviderDefinition::key)
797 .collect();
798 for imported in modules
799 .values()
800 .filter(|candidate| candidate.global || module.imports.contains(&candidate.name))
801 {
802 visible.extend(imported.exports.iter().copied());
803 }
804 for provider in &module.providers {
805 for dependency in &provider.dependencies {
806 let registered = modules.values().any(|candidate| {
807 candidate
808 .providers
809 .iter()
810 .any(|provider| provider.key == *dependency)
811 });
812 if registered && !visible.contains(dependency) {
813 return Err(InjectError::PrivateProviderAccess {
814 provider: dependency.name,
815 module: module.name,
816 });
817 }
818 }
819 }
820 }
821 let mut builder = Container::builder();
822 for module in modules.into_values() {
823 for provider in module.providers {
824 builder = builder.provider(provider);
825 }
826 }
827 for replacement in overrides {
828 builder = builder.override_provider(replacement);
829 }
830 builder.build()
831 }
832}
833
834pub trait Injectable: Sized {
837 fn inject(injector: &Injector) -> Result<Self, InjectError>;
839}
840impl<T: Injectable + 'static> Injectable for Arc<T> {
841 fn inject(injector: &Injector) -> Result<Self, InjectError> {
843 injector.resolve::<T>().map(Arc::new)
844 }
845}
846pub struct Injector {
848 values: HashMap<TypeId, Box<dyn Any>>,
849}
850thread_local! { static PATH: RefCell<Vec<&'static str>> = const { RefCell::new(Vec::new()) }; }
851impl Injector {
852 #[must_use]
853 pub fn new() -> Self {
855 Self {
856 values: HashMap::new(),
857 }
858 }
859 #[must_use]
860 pub fn value<T: Clone + 'static>(mut self, value: T) -> Self {
862 self.values.insert(TypeId::of::<T>(), Box::new(value));
863 self
864 }
865 pub fn resolve<T: Injectable + 'static>(&self) -> Result<T, InjectError> {
867 let name = type_name::<T>();
868 PATH.with(|path| {
869 let mut path = path.borrow_mut();
870 if let Some(index) = path.iter().position(|entry| *entry == name) {
871 let mut chain = path[index..].to_vec();
872 chain.push(name);
873 return Err(InjectError::Circular(chain));
874 }
875 path.push(name);
876 drop(path);
877 let result = T::inject(self);
878 PATH.with(|path| {
879 path.borrow_mut().pop();
880 });
881 result
882 })
883 }
884 pub fn value_of<T: Clone + 'static>(&self) -> Result<T, InjectError> {
886 self.values
887 .get(&TypeId::of::<T>())
888 .and_then(|value| value.downcast_ref::<T>())
889 .cloned()
890 .ok_or(InjectError::Missing(type_name::<T>()))
891 }
892}
893impl Default for Injector {
894 fn default() -> Self {
895 Self::new()
896 }
897}
898
899#[cfg(test)]
900mod tests {
901 use super::*;
902 struct A;
903 impl Provider for A {
904 fn provide(_: &Container) -> Result<Self, InjectError> {
906 Ok(Self)
907 }
908 }
909 #[test]
910 fn singleton_is_cached() {
911 let c = Container::builder().injectable::<A>().build().unwrap();
912 assert!(Arc::ptr_eq(
913 &c.resolve::<A>().unwrap(),
914 &c.resolve::<A>().unwrap()
915 ));
916 }
917}