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
//! Dependency scopes
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::{Arc, PoisonError, RwLock};
/// Defines the lifetime scope of a dependency.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
/// A new instance is created for each request.
Request,
/// A single instance is shared across the entire application lifetime.
Singleton,
}
/// Per-request dependency cache that stores resolved instances for the duration of a request.
#[derive(Clone)]
pub struct RequestScope {
cache: Arc<RwLock<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>>,
}
impl RequestScope {
/// Creates a new RequestScope with an empty cache.
///
/// # Examples
///
/// ```
/// use reinhardt_di::RequestScope;
///
/// let scope = RequestScope::new();
/// ```
pub fn new() -> Self {
Self {
cache: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Retrieves a value from the request scope cache by type.
///
/// Returns `None` if no value of type `T` exists in the cache.
///
/// # Examples
///
/// ```
/// use reinhardt_di::RequestScope;
///
/// let scope = RequestScope::new();
/// scope.set(42i32);
///
/// let value = scope.get::<i32>().unwrap();
/// assert_eq!(*value, 42);
/// ```
pub fn get<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
let cache = self.cache.read().unwrap_or_else(PoisonError::into_inner);
let type_id = TypeId::of::<T>();
cache
.get(&type_id)
.and_then(|arc| arc.clone().downcast::<T>().ok())
}
/// Stores a value in the request scope cache.
///
/// The value is stored by its type and can be retrieved later using `get`.
///
/// # Examples
///
/// ```
/// use reinhardt_di::RequestScope;
///
/// let scope = RequestScope::new();
/// scope.set(42i32);
/// scope.set("hello".to_string());
///
/// assert_eq!(*scope.get::<i32>().unwrap(), 42);
/// assert_eq!(*scope.get::<String>().unwrap(), "hello");
/// ```
pub fn set<T: Any + Send + Sync>(&self, value: T) {
let mut cache = self.cache.write().unwrap_or_else(PoisonError::into_inner);
let type_id = TypeId::of::<T>();
cache.insert(type_id, Arc::new(value));
}
/// Stores a pre-wrapped `Arc<T>` in the request scope cache.
///
/// Unlike `set`, this method accepts an already-wrapped Arc value,
/// avoiding the need to unwrap and re-wrap. This is useful when
/// the value is produced by a factory that returns `Arc<T>`.
///
/// # Examples
///
/// ```
/// use reinhardt_di::RequestScope;
/// use std::sync::Arc;
///
/// let scope = RequestScope::new();
/// let value = Arc::new(42i32);
/// scope.set_arc(value);
///
/// assert_eq!(*scope.get::<i32>().unwrap(), 42);
/// ```
pub fn set_arc<T: Any + Send + Sync>(&self, value: Arc<T>) {
let mut cache = self.cache.write().unwrap_or_else(PoisonError::into_inner);
let type_id = TypeId::of::<T>();
cache.insert(type_id, value);
}
}
impl RequestScope {
/// Creates a deep clone of this scope with an independent cache.
///
/// The cloned scope contains the same cached entries as the original,
/// but modifications to either scope will not affect the other.
pub fn deep_clone(&self) -> Self {
let cache = self.cache.read().unwrap_or_else(PoisonError::into_inner);
Self {
cache: Arc::new(RwLock::new(cache.clone())),
}
}
}
impl Default for RequestScope {
fn default() -> Self {
Self::new()
}
}
/// Application-wide dependency cache that persists across all requests.
pub struct SingletonScope {
cache: Arc<RwLock<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>>,
}
impl SingletonScope {
/// Creates a new SingletonScope with an empty cache.
///
/// # Examples
///
/// ```
/// use reinhardt_di::SingletonScope;
///
/// let scope = SingletonScope::new();
/// ```
pub fn new() -> Self {
Self {
cache: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Retrieves a singleton value from the cache by type.
///
/// Returns `None` if no value of type `T` exists in the singleton cache.
///
/// # Examples
///
/// ```
/// use reinhardt_di::SingletonScope;
///
/// let scope = SingletonScope::new();
/// scope.set(100u64);
///
/// let value = scope.get::<u64>().unwrap();
/// assert_eq!(*value, 100);
/// ```
pub fn get<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
let cache = self.cache.read().unwrap_or_else(PoisonError::into_inner);
let type_id = TypeId::of::<T>();
cache
.get(&type_id)
.and_then(|arc| arc.clone().downcast::<T>().ok())
}
/// Stores a singleton value in the cache.
///
/// The value persists across multiple requests and is shared application-wide.
///
/// # Examples
///
/// ```
/// use reinhardt_di::SingletonScope;
///
/// let scope = SingletonScope::new();
/// scope.set(42i32);
///
/// // Same value retrieved across multiple calls
/// let val1 = scope.get::<i32>().unwrap();
/// let val2 = scope.get::<i32>().unwrap();
/// assert_eq!(*val1, *val2);
/// ```
pub fn set<T: Any + Send + Sync>(&self, value: T) {
let mut cache = self.cache.write().unwrap_or_else(PoisonError::into_inner);
let type_id = TypeId::of::<T>();
cache.insert(type_id, Arc::new(value));
}
/// Stores a pre-wrapped `Arc<T>` in the singleton scope cache.
///
/// Unlike `set`, this method accepts an already-wrapped Arc value,
/// avoiding the need to unwrap and re-wrap. This is useful when
/// the value is produced by a factory that returns `Arc<T>`.
///
/// # Examples
///
/// ```
/// use reinhardt_di::SingletonScope;
/// use std::sync::Arc;
///
/// let scope = SingletonScope::new();
/// let value = Arc::new(42i32);
/// scope.set_arc(value);
///
/// assert_eq!(*scope.get::<i32>().unwrap(), 42);
/// ```
pub fn set_arc<T: Any + Send + Sync>(&self, value: Arc<T>) {
let mut cache = self.cache.write().unwrap_or_else(PoisonError::into_inner);
let type_id = TypeId::of::<T>();
cache.insert(type_id, value);
}
/// Inserts a pre-erased `Arc<dyn Any + Send + Sync>` keyed by an explicit
/// `TypeId`.
///
/// This is the type-erased counterpart of [`set_arc`](Self::set_arc) and
/// is intended for callers (such as the `Middleware::di_registrations`
/// bridge in `reinhardt-urls`) that have already type-erased the value to
/// avoid a circular crate dependency on `reinhardt-di`.
pub fn set_arc_any(&self, type_id: TypeId, value: Arc<dyn Any + Send + Sync>) {
let mut cache = self.cache.write().unwrap_or_else(PoisonError::into_inner);
cache.insert(type_id, value);
}
}
impl Default for SingletonScope {
fn default() -> Self {
Self::new()
}
}