reinhardt-di 0.1.3

Dependency injection system for Reinhardt, inspired by FastAPI
Documentation
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
//! Injected wrapper for dependency injection
//!
//! FastAPI-inspired dependency injection wrapper that provides:
//! - Automatic dependency resolution
//! - Caching control via scope and cache flag
//! - Type-safe dependency injection with metadata
//!
//! # Examples
//!
//! ```
//! use reinhardt_di::{Injected, OptionalInjected, Injectable, InjectionContext};
//!
//! # #[derive(Clone, Default)]
//! # struct Database;
//! # #[derive(Clone, Default)]
//! # struct Cache;
//! #
//! # #[async_trait::async_trait]
//! # impl Injectable for Database {
//! #     async fn inject(ctx: &InjectionContext) -> reinhardt_di::DiResult<Self> {
//! #         Ok(Database::default())
//! #     }
//! # }
//! #
//! # #[async_trait::async_trait]
//! # impl Injectable for Cache {
//! #     async fn inject(ctx: &InjectionContext) -> reinhardt_di::DiResult<Self> {
//! #         Ok(Cache::default())
//! #     }
//! # }
//! #
//! async fn handler(
//!     db: Injected<Database>,
//!     optional_cache: OptionalInjected<Cache>,
//! ) -> String {
//!     // db is always available
//!     // optional_cache can be treated as Option<Injected<Cache>>
//!     "OK".to_string()
//! }
//! ```

use crate::{
	DiError, DiResult, Injectable, InjectionContext, begin_resolution, with_cycle_detection_scope,
};
use std::any::TypeId;
use std::ops::Deref;
use std::sync::Arc;

/// Injection metadata
///
/// Tracks the scope and caching status of an injected dependency.
#[derive(Debug, Clone, Copy)]
pub struct InjectionMetadata {
	/// Dependency scope (Request or Singleton)
	pub scope: DependencyScope,
	/// Whether caching was enabled during resolution
	pub cached: bool,
}

/// Dependency scope
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependencyScope {
	/// Request-scoped dependency (lifetime tied to request)
	Request,
	/// Singleton-scoped dependency (shared across requests)
	Singleton,
}

/// Injected dependency wrapper
///
/// Wraps an `Arc<T>` with injection metadata, providing:
/// - Shared ownership via `Arc`
/// - Metadata tracking (scope, cache status)
/// - Transparent access via `Deref`
///
/// # Examples
///
/// ```
/// use reinhardt_di::{Injected, InjectionContext, Injectable, SingletonScope};
/// use std::sync::Arc;
///
/// # #[derive(Clone, Default)]
/// # struct Config;
/// #
/// # #[async_trait::async_trait]
/// # impl Injectable for Config {
/// #     async fn inject(ctx: &InjectionContext) -> reinhardt_di::DiResult<Self> {
/// #         Ok(Config::default())
/// #     }
/// # }
/// #
/// # async fn example() -> reinhardt_di::DiResult<()> {
/// let singleton_scope = Arc::new(SingletonScope::new());
/// let ctx = InjectionContext::builder(singleton_scope).build();
///
/// // Resolve with cache enabled (default)
/// let config1 = Injected::<Config>::resolve(&ctx).await?;
/// let config2 = Injected::<Config>::resolve(&ctx).await?;
///
/// // Resolve without cache
/// let config3 = Injected::<Config>::resolve_uncached(&ctx).await?;
/// # Ok(())
/// # }
/// ```
#[deprecated(
	since = "0.1.0-rc.16",
	note = "use `Depends<T>` instead. `Injected<T>` will be removed in a future version."
)]
#[derive(Debug)]
pub struct Injected<T: Injectable> {
	inner: Arc<T>,
	metadata: InjectionMetadata,
}

#[allow(deprecated)]
impl<T: Injectable> Injected<T> {
	/// Resolve dependency with cache enabled (default)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Injected, InjectionContext, Injectable, SingletonScope};
	/// use std::sync::Arc;
	///
	/// # #[derive(Clone, Default)]
	/// # struct Config;
	/// #
	/// # #[async_trait::async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(ctx: &InjectionContext) -> reinhardt_di::DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	/// #
	/// # async fn example() -> reinhardt_di::DiResult<()> {
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	/// let config = Injected::<Config>::resolve(&ctx).await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn resolve(ctx: &InjectionContext) -> DiResult<Self> {
		Self::resolve_with_cache(ctx, true).await
	}

	/// Resolve dependency without cache
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Injected, InjectionContext, Injectable, SingletonScope};
	/// use std::sync::Arc;
	///
	/// # #[derive(Clone, Default)]
	/// # struct Config;
	/// #
	/// # #[async_trait::async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(ctx: &InjectionContext) -> reinhardt_di::DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	/// #
	/// # async fn example() -> reinhardt_di::DiResult<()> {
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	/// let config = Injected::<Config>::resolve_uncached(&ctx).await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn resolve_uncached(ctx: &InjectionContext) -> DiResult<Self> {
		Self::resolve_with_cache(ctx, false).await
	}

	/// Resolve dependency with cache control (internal use)
	///
	/// # Arguments
	///
	/// * `ctx` - Injection context
	/// * `use_cache` - Whether to use request-scoped cache
	async fn resolve_with_cache(ctx: &InjectionContext, use_cache: bool) -> DiResult<Self> {
		with_cycle_detection_scope(async {
			let inner = if use_cache {
				// Check request cache first
				if let Some(cached) = ctx.get_request::<T>() {
					cached
				} else {
					// Begin circular dependency detection
					let type_id = TypeId::of::<T>();
					let type_name = std::any::type_name::<T>();
					let _guard = begin_resolution(type_id, type_name)
						.map_err(|e| DiError::CircularDependency(e.to_string()))?;

					let v = T::inject(ctx).await?;
					let arc = Arc::new(v);
					ctx.set_request_arc(Arc::clone(&arc));
					arc
				}
			} else {
				// Begin circular dependency detection (even for uncached)
				let type_id = TypeId::of::<T>();
				let type_name = std::any::type_name::<T>();
				let _guard = begin_resolution(type_id, type_name)
					.map_err(|e| DiError::CircularDependency(e.to_string()))?;

				// Skip cache
				Arc::new(T::inject_uncached(ctx).await?)
			};

			Ok(Self {
				inner,
				metadata: InjectionMetadata {
					scope: DependencyScope::Request,
					cached: use_cache,
				},
			})
		})
		.await
	}

	/// Create from value for testing
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Injected, Injectable};
	///
	/// # #[derive(Clone, Default)]
	/// # struct Database {
	/// #     connection_count: usize,
	/// # }
	/// #
	/// # #[async_trait::async_trait]
	/// # impl Injectable for Database {
	/// #     async fn inject(ctx: &reinhardt_di::InjectionContext) -> reinhardt_di::DiResult<Self> {
	/// #         Ok(Database::default())
	/// #     }
	/// # }
	/// #
	/// let db = Database { connection_count: 10 };
	/// let injected = Injected::from_value(db);
	/// assert_eq!(injected.connection_count, 10);
	/// ```
	pub fn from_value(value: T) -> Self {
		Self {
			inner: Arc::new(value),
			metadata: InjectionMetadata {
				scope: DependencyScope::Request,
				cached: false,
			},
		}
	}

	/// Get Arc reference
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Injected, Injectable};
	/// use std::sync::Arc;
	///
	/// # #[derive(Clone, Default)]
	/// # struct Config;
	/// #
	/// # #[async_trait::async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(ctx: &reinhardt_di::InjectionContext) -> reinhardt_di::DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	/// #
	/// let injected = Injected::from_value(Config::default());
	/// let arc: &Arc<Config> = injected.as_arc();
	/// ```
	pub fn as_arc(&self) -> &Arc<T> {
		&self.inner
	}

	/// Get injection metadata
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Injected, Injectable};
	///
	/// # #[derive(Clone, Default)]
	/// # struct Config;
	/// #
	/// # #[async_trait::async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(ctx: &reinhardt_di::InjectionContext) -> reinhardt_di::DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	/// #
	/// let injected = Injected::from_value(Config::default());
	/// let metadata = injected.metadata();
	/// assert!(!metadata.cached);
	/// ```
	pub fn metadata(&self) -> &InjectionMetadata {
		&self.metadata
	}

	/// Attempt to unwrap the inner `Arc`, returning `T` if this is the only
	/// strong reference. Returns `Err(Self)` if other references exist.
	///
	/// This mirrors [`Arc::try_unwrap`] semantics. Unlike
	/// [`into_inner`](Injected::into_inner), this method does **not** require
	/// `T: Clone`.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Injected, Injectable};
	///
	/// # #[derive(Clone, Debug, Default)]
	/// # struct Config;
	/// #
	/// # #[async_trait::async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(ctx: &reinhardt_di::InjectionContext) -> reinhardt_di::DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	/// #
	/// let injected = Injected::from_value(Config::default());
	/// let config = injected.try_unwrap().unwrap();
	/// ```
	pub fn try_unwrap(self) -> Result<T, Self> {
		match Arc::try_unwrap(self.inner) {
			Ok(val) => Ok(val),
			Err(arc) => Err(Self {
				inner: arc,
				metadata: self.metadata,
			}),
		}
	}
}

#[allow(deprecated)]
impl<T: Injectable + Clone> Injected<T> {
	/// Extract inner value
	///
	/// This method tries to unwrap the Arc. If the Arc has multiple strong references,
	/// it clones the inner value instead. Requires `T: Clone`.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Injected, Injectable};
	///
	/// # #[derive(Clone, Default)]
	/// # struct Config;
	/// #
	/// # #[async_trait::async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(ctx: &reinhardt_di::InjectionContext) -> reinhardt_di::DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	/// #
	/// let injected = Injected::from_value(Config::default());
	/// let config = injected.into_inner();
	/// ```
	pub fn into_inner(self) -> T {
		Arc::try_unwrap(self.inner).unwrap_or_else(|arc| (*arc).clone())
	}
}

#[allow(deprecated)]
impl<T: Injectable> Deref for Injected<T> {
	type Target = T;

	fn deref(&self) -> &Self::Target {
		&self.inner
	}
}

#[allow(deprecated)]
impl<T: Injectable> Clone for Injected<T> {
	fn clone(&self) -> Self {
		Self {
			inner: Arc::clone(&self.inner),
			metadata: self.metadata,
		}
	}
}

#[allow(deprecated)]
impl<T: Injectable> AsRef<T> for Injected<T> {
	fn as_ref(&self) -> &T {
		&self.inner
	}
}

/// Optional injected dependency
///
/// Type alias for `Option<Injected<T>>`, used for optional dependencies.
///
/// # Critical Constraint
///
/// When using `#[inject]` attribute:
/// - `#[inject(optional = true)]` → **MUST** use `OptionalInjected<T>` type
/// - `#[inject(optional = false)]` or `#[inject]` → **MUST** use `Injected<T>` type
/// - Type/attribute mismatches will cause compile errors
///
/// # Examples
///
/// ```
/// use reinhardt_di::{Injected, OptionalInjected};
///
/// // ✅ Correct: optional = true with OptionalInjected<T>
/// // #[get("/data", use_inject = true)]
/// // async fn handler(
/// //     #[inject(optional = true)] cache: OptionalInjected<RedisCache>,
/// // ) -> Result<String> {
/// //     if let Some(cache) = cache {
/// //         Ok(cache.get("data").await?)
/// //     } else {
/// //         Ok("No cache available".to_string())
/// //     }
/// // }
///
/// // ✅ Correct: no optional (default false) with Injected<T>
/// // #[get("/users", use_inject = true)]
/// // async fn list_users(
/// //     #[inject] db: Injected<Database>,
/// // ) -> Result<String> {
/// //     Ok(db.query("SELECT * FROM users").await?)
/// // }
///
/// // ❌ Error: optional = true but type is Injected<T>
/// // #[get("/bad", use_inject = true)]
/// // async fn bad_handler(
/// //     #[inject(optional = true)] cache: Injected<RedisCache>,
/// //     //                                  ^^^^^^^^^^^^^^^^^ Error!
/// // ) -> Result<String> { ... }
///
/// // ❌ Error: optional = false but type is OptionalInjected<T>
/// // #[get("/bad2", use_inject = true)]
/// // async fn bad_handler2(
/// //     #[inject(optional = false)] db: OptionalInjected<Database>,
/// //     //                               ^^^^^^^^^^^^^^^^^^^^^^^^^ Error!
/// // ) -> Result<String> { ... }
/// ```
#[deprecated(
	since = "0.1.0-rc.16",
	note = "use `Option<Depends<T>>` instead. `OptionalInjected<T>` will be removed in a future version."
)]
#[allow(deprecated)]
pub type OptionalInjected<T> = Option<Injected<T>>;

#[cfg(test)]
#[allow(deprecated)]
mod tests {
	use super::*;
	use crate::SingletonScope;

	#[derive(Clone, Default, Debug)]
	struct TestConfig {
		value: String,
	}

	#[async_trait::async_trait]
	impl Injectable for TestConfig {
		async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
			Ok(TestConfig {
				value: "test".to_string(),
			})
		}
	}

	#[tokio::test]
	async fn test_injected_from_value() {
		let config = TestConfig {
			value: "custom".to_string(),
		};
		let injected = Injected::from_value(config);
		assert_eq!(injected.value, "custom");
	}

	#[tokio::test]
	async fn test_injected_into_inner() {
		let config = TestConfig {
			value: "test".to_string(),
		};
		let injected = Injected::from_value(config);
		let extracted = injected.into_inner();
		assert_eq!(extracted.value, "test");
	}

	#[tokio::test]
	async fn test_injected_clone() {
		let config = TestConfig {
			value: "test".to_string(),
		};
		let injected1 = Injected::from_value(config);
		let injected2 = injected1.clone();

		assert_eq!(injected1.value, "test");
		assert_eq!(injected2.value, "test");
	}

	#[tokio::test]
	async fn test_injected_deref() {
		let config = TestConfig {
			value: "test".to_string(),
		};
		let injected = Injected::from_value(config);

		// Can be accessed directly via Deref
		assert_eq!(injected.value, "test");
	}

	#[tokio::test]
	async fn test_injected_metadata() {
		let config = TestConfig {
			value: "test".to_string(),
		};
		let injected = Injected::from_value(config);

		let metadata = injected.metadata();
		assert_eq!(metadata.scope, DependencyScope::Request);
		assert!(!metadata.cached);
	}

	#[tokio::test]
	async fn test_optional_injected_some() {
		let config = TestConfig {
			value: "test".to_string(),
		};
		let optional: OptionalInjected<TestConfig> = Some(Injected::from_value(config));

		assert!(optional.is_some());
		if let Some(injected) = optional {
			assert_eq!(injected.value, "test");
		}
	}

	#[tokio::test]
	async fn test_optional_injected_none() {
		let optional: OptionalInjected<TestConfig> = None;
		assert!(optional.is_none());
	}

	// Additional dependency scope tests

	#[test]
	fn test_dependency_scope_equality() {
		assert_eq!(DependencyScope::Request, DependencyScope::Request);
		assert_eq!(DependencyScope::Singleton, DependencyScope::Singleton);
		assert_ne!(DependencyScope::Request, DependencyScope::Singleton);
	}

	#[test]
	fn test_dependency_scope_debug() {
		let request = DependencyScope::Request;
		let singleton = DependencyScope::Singleton;

		let request_debug = format!("{:?}", request);
		let singleton_debug = format!("{:?}", singleton);

		assert!(request_debug.contains("Request"));
		assert!(singleton_debug.contains("Singleton"));
	}

	#[test]
	fn test_dependency_scope_clone() {
		let request = DependencyScope::Request;
		let cloned = request;

		assert_eq!(request, cloned);
	}

	#[test]
	fn test_injection_metadata_debug() {
		let metadata = InjectionMetadata {
			scope: DependencyScope::Request,
			cached: true,
		};

		let debug_str = format!("{:?}", metadata);

		assert!(debug_str.contains("InjectionMetadata"));
		assert!(debug_str.contains("Request"));
		assert!(debug_str.contains("true"));
	}

	#[test]
	fn test_injection_metadata_clone() {
		let metadata = InjectionMetadata {
			scope: DependencyScope::Singleton,
			cached: false,
		};

		let cloned = metadata;

		assert_eq!(cloned.scope, DependencyScope::Singleton);
		assert!(!cloned.cached);
	}

	#[test]
	fn test_injection_metadata_copy() {
		let metadata = InjectionMetadata {
			scope: DependencyScope::Request,
			cached: true,
		};

		// InjectionMetadata derives Copy
		fn takes_copy<T: Copy>(_: T) {}
		takes_copy(metadata);

		// Original is still valid after copy
		assert_eq!(metadata.scope, DependencyScope::Request);
		assert!(metadata.cached);
	}

	#[tokio::test]
	async fn test_injected_as_arc() {
		let config = TestConfig {
			value: "arc_test".to_string(),
		};
		let injected = Injected::from_value(config);

		let arc = injected.as_arc();

		// Arc reference provides access to inner value
		assert_eq!(arc.value, "arc_test");

		// Arc strong count should be 1 (only one reference)
		assert_eq!(Arc::strong_count(arc), 1);
	}

	#[tokio::test]
	async fn test_injected_as_ref() {
		let config = TestConfig {
			value: "ref_test".to_string(),
		};
		let injected = Injected::from_value(config);

		// AsRef trait implementation
		let reference: &TestConfig = injected.as_ref();
		assert_eq!(reference.value, "ref_test");
	}

	#[tokio::test]
	async fn test_injected_debug() {
		let config = TestConfig {
			value: "debug_test".to_string(),
		};
		let injected = Injected::from_value(config);

		let debug_str = format!("{:?}", injected);

		assert!(debug_str.contains("Injected"));
	}

	#[tokio::test]
	async fn test_injected_resolve_with_context() {
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		let config = Injected::<TestConfig>::resolve(&ctx).await.unwrap();

		assert_eq!(config.value, "test");
		assert!(config.metadata().cached);
		assert_eq!(config.metadata().scope, DependencyScope::Request);
	}

	#[tokio::test]
	async fn test_injected_resolve_uncached_with_context() {
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		let config = Injected::<TestConfig>::resolve_uncached(&ctx)
			.await
			.unwrap();

		assert_eq!(config.value, "test");
		assert!(!config.metadata().cached);
	}

	#[tokio::test]
	async fn test_injected_clone_shares_arc() {
		let config = TestConfig {
			value: "shared".to_string(),
		};
		let injected1 = Injected::from_value(config);
		let injected2 = injected1.clone();

		// Both should share the same Arc
		assert_eq!(Arc::strong_count(injected1.as_arc()), 2);
		assert_eq!(Arc::strong_count(injected2.as_arc()), 2);

		// Both point to the same data
		assert!(Arc::ptr_eq(injected1.as_arc(), injected2.as_arc()));
	}

	#[tokio::test]
	async fn test_injected_metadata_preserved_on_clone() {
		let config = TestConfig {
			value: "metadata".to_string(),
		};
		let injected1 = Injected::from_value(config);
		let injected2 = injected1.clone();

		// Metadata should be identical
		assert_eq!(injected1.metadata().scope, injected2.metadata().scope);
		assert_eq!(injected1.metadata().cached, injected2.metadata().cached);
	}

	#[tokio::test]
	async fn test_injected_into_inner_with_single_reference() {
		let config = TestConfig {
			value: "single".to_string(),
		};
		let injected = Injected::from_value(config);

		// With single reference, Arc::try_unwrap succeeds
		let inner = injected.into_inner();
		assert_eq!(inner.value, "single");
	}

	#[tokio::test]
	async fn test_injected_into_inner_with_multiple_references() {
		let config = TestConfig {
			value: "multiple".to_string(),
		};
		let injected1 = Injected::from_value(config);
		let _injected2 = injected1.clone(); // Create second reference

		// With multiple references, Arc::try_unwrap fails, falls back to clone
		let inner = injected1.into_inner();
		assert_eq!(inner.value, "multiple");
	}

	/// `try_unwrap()` succeeds when there is only one strong reference.
	#[tokio::test]
	async fn test_injected_try_unwrap_success() {
		// Arrange
		let config = TestConfig {
			value: "owned".to_string(),
		};
		let injected = Injected::from_value(config);

		// Act
		let result = injected.try_unwrap();

		// Assert
		assert!(result.is_ok());
		assert_eq!(result.unwrap().value, "owned");
	}

	/// `try_unwrap()` returns `Err(Self)` when multiple references exist.
	#[tokio::test]
	async fn test_injected_try_unwrap_err_multiple_refs() {
		// Arrange
		let config = TestConfig {
			value: "shared".to_string(),
		};
		let injected = Injected::from_value(config);
		let _clone = injected.clone();

		// Act
		let result = injected.try_unwrap();

		// Assert
		let returned = result.unwrap_err();
		assert_eq!(returned.value, "shared");
		assert_eq!(returned.metadata().scope, DependencyScope::Request);
	}
}