dependency_injector/
provider.rs1use std::any::TypeId;
6
7pub trait Injectable: Send + Sync + 'static {
24 #[inline]
26 fn type_id_of() -> TypeId
27 where
28 Self: Sized,
29 {
30 TypeId::of::<Self>()
31 }
32
33 #[inline]
35 fn type_name_of() -> &'static str
36 where
37 Self: Sized,
38 {
39 std::any::type_name::<Self>()
40 }
41}
42
43impl<T: Send + Sync + 'static> Injectable for T {}
45
46pub trait Provider: Injectable {}
48impl<T: Injectable> Provider for T {}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
52pub enum Lifetime {
53 #[default]
55 Singleton,
56
57 Lazy,
59
60 Transient,
62
63 Scoped,
65}
66
67#[derive(Clone)]
69pub struct ProviderRegistration {
70 pub type_id: TypeId,
72 pub type_name: &'static str,
74 pub register_fn: fn(&crate::Container),
76}
77
78impl ProviderRegistration {
79 #[inline]
81 pub fn new<T: Injectable>(register_fn: fn(&crate::Container)) -> Self {
82 Self {
83 type_id: TypeId::of::<T>(),
84 type_name: std::any::type_name::<T>(),
85 register_fn,
86 }
87 }
88
89 pub fn singleton<T: Injectable + Clone>(_value: T) -> Self {
94 Self {
95 type_id: TypeId::of::<T>(),
96 type_name: std::any::type_name::<T>(),
97 register_fn: |_container| {
98 },
100 }
101 }
102}
103
104impl std::fmt::Debug for ProviderRegistration {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 f.debug_struct("ProviderRegistration")
107 .field("type_id", &self.type_id)
108 .field("type_name", &self.type_name)
109 .finish()
110 }
111}
112
113#[macro_export]
115macro_rules! provider {
116 ($type:ty, $factory:expr) => {
117 $crate::ProviderRegistration {
118 type_id: std::any::TypeId::of::<$type>(),
119 type_name: std::any::type_name::<$type>(),
120 register_fn: |container| {
121 container.singleton($factory);
122 },
123 }
124 };
125 (lazy $type:ty, $factory:expr) => {
126 $crate::ProviderRegistration {
127 type_id: std::any::TypeId::of::<$type>(),
128 type_name: std::any::type_name::<$type>(),
129 register_fn: |container| {
130 container.lazy($factory);
131 },
132 }
133 };
134 (transient $type:ty, $factory:expr) => {
135 $crate::ProviderRegistration {
136 type_id: std::any::TypeId::of::<$type>(),
137 type_name: std::any::type_name::<$type>(),
138 register_fn: |container| {
139 container.transient($factory);
140 },
141 }
142 };
143}