reinhardt-di 0.2.2

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
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
//! Depends wrapper for dependency injection
//!
//! FastAPI-inspired dependency injection wrapper that provides:
//! - Automatic dependency resolution
//! - Circular dependency detection
//! - Caching control via `use_cache` parameter
//! - Type-safe dependency injection with metadata
//!
//! ## Examples
//!
//! ```rust,no_run
//! use reinhardt_di::{Depends, DiResult, Injectable, InjectionContext, SingletonScope, global_registry, DependencyScope};
//! # use async_trait::async_trait;
//! use std::sync::Arc;
//!
//! #[derive(Default)]
//! struct Config {
//!     database_url: String,
//! }
//!
//! # #[async_trait]
//! # impl Injectable for Config {
//! #     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
//! #         Ok(Config::default())
//! #     }
//! # }
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Register Config in the global registry (normally done via #[injectable] or #[injectable_factory])
//! let registry = global_registry();
//! registry.register_async::<Config, _, _>(DependencyScope::Request, |_ctx| async {
//!     Ok(Config::default())
//! });
//!
//! let singleton = Arc::new(SingletonScope::new());
//! let ctx = InjectionContext::builder(singleton).build();
//!
//! // Basic usage - with caching (default)
//! let config = Depends::<Config>::builder().resolve(&ctx).await?;
//!
//! // Without caching flag - caching behavior is determined by the registered
//! // DependencyScope (Singleton/Request/Transient), not by this flag.
//! let config = Depends::<Config>::builder_no_cache().resolve(&ctx).await?;
//! # Ok(())
//! # }
//! ```

use crate::injected::DependencyScope;
use crate::{
	DiError, DiResult, Injectable, context::InjectionContext, injected::InjectionMetadata,
};
use std::ops::Deref;
use std::sync::Arc;

/// Dependency injection wrapper similar to FastAPI's Depends.
///
/// Provides automatic dependency resolution with optional caching
/// and circular dependency detection.
///
/// Two resolution methods are available:
/// - [`resolve()`](Self::resolve): Resolves via the global registry first,
///   falling back to `T::inject()` for types with manual `Injectable`
///   implementations. Requires `T: Injectable`.
/// - [`resolve_from_registry()`](Self::resolve_from_registry): Resolves via
///   the global registry only. Does not require `T: Injectable`. Used by
///   `#[injectable_factory]` for factory-produced types.
#[derive(Debug)]
pub struct Depends<T: Send + Sync + 'static> {
	inner: Arc<T>,
	metadata: InjectionMetadata,
}

impl<T: Send + Sync + 'static> Depends<T> {
	/// Create a new DependsBuilder with caching enabled (default behavior).
	///
	/// Similar to FastAPI's `Depends(dependency, use_cache=True)`.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Depends, Injectable, InjectionContext, DiResult};
	/// # use async_trait::async_trait;
	///
	/// #[derive(Clone, Default)]
	/// struct Config {
	///     value: String,
	/// }
	///
	/// # #[async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	///
	/// let builder = Depends::<Config>::builder();
	/// ```
	pub fn builder() -> DependsBuilder<T> {
		DependsBuilder {
			use_cache: true,
			_phantom: std::marker::PhantomData,
		}
	}
	/// Create a new DependsBuilder with caching disabled.
	///
	/// Similar to FastAPI's `Depends(dependency, use_cache=False)`.
	/// Each call will create a new instance.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Depends, Injectable, InjectionContext, DiResult};
	/// # use async_trait::async_trait;
	///
	/// #[derive(Clone, Default)]
	/// struct RequestData {
	///     id: u32,
	/// }
	///
	/// # #[async_trait]
	/// # impl Injectable for RequestData {
	/// #     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
	/// #         Ok(RequestData::default())
	/// #     }
	/// # }
	///
	/// let builder = Depends::<RequestData>::builder_no_cache();
	/// ```
	pub fn builder_no_cache() -> DependsBuilder<T> {
		DependsBuilder {
			use_cache: false,
			_phantom: std::marker::PhantomData,
		}
	}
	/// Resolve the dependency from the injection context.
	///
	/// This method delegates to `ctx.resolve::<T>()` which:
	/// 1. Detects circular dependencies
	/// 2. Checks scope caches (singleton/request)
	/// 3. Calls the registered factory if not cached
	///
	/// If the type is not in the global registry, falls back to `T::inject()`
	/// for types with manual `Injectable` implementations.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Depends, InjectionContext, SingletonScope, Injectable, DiResult};
	/// # use async_trait::async_trait;
	/// use std::sync::Arc;
	///
	/// #[derive(Clone, Default)]
	/// struct Config {
	///     value: String,
	/// }
	///
	/// # #[async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	///
	/// # async fn example() -> DiResult<()> {
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	/// let result = Depends::<Config>::resolve(&ctx, true).await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn resolve(ctx: &InjectionContext, use_cache: bool) -> DiResult<Self>
	where
		T: Injectable,
	{
		// Resolve via the global dependency registry first.
		// If the type is not registered (e.g., manual `impl Injectable` without
		// `#[injectable]`), fall back to `T::inject()` directly.
		let arc = match ctx.resolve::<T>().await {
			Ok(arc) => arc,
			Err(DiError::DependencyNotRegistered { .. }) => Arc::new(T::inject(ctx).await?),
			Err(e) => return Err(e),
		};

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

	/// Resolve the dependency from the global registry only.
	///
	/// Unlike [`resolve()`](Self::resolve), this method does **not** require
	/// `T: Injectable` and does **not** fall back to `T::inject()`. It returns
	/// an error if the type is not registered in the global registry.
	///
	/// This is the method used by `#[injectable_factory]` for dependency
	/// resolution, allowing factory-produced types to be injected without an
	/// `Injectable` implementation.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Depends, InjectionContext, SingletonScope, DiResult, global_registry, DependencyScope};
	/// use std::sync::Arc;
	///
	/// #[derive(Clone, Default)]
	/// struct Config {
	///     value: String,
	/// }
	///
	/// # async fn example() -> DiResult<()> {
	/// // Register via factory (no Injectable impl needed)
	/// let registry = global_registry();
	/// registry.register_async::<Config, _, _>(DependencyScope::Singleton, |_ctx| async {
	///     Ok(Config::default())
	/// });
	///
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	/// let result = Depends::<Config>::resolve_from_registry(&ctx, true).await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn resolve_from_registry(ctx: &InjectionContext, use_cache: bool) -> DiResult<Self> {
		let arc = ctx.resolve::<T>().await?;

		Ok(Self {
			inner: arc,
			metadata: InjectionMetadata {
				scope: DependencyScope::Request,
				cached: use_cache,
			},
		})
	}
	/// Create a Depends from an existing value (for testing).
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Depends, Injectable, InjectionContext, DiResult};
	/// # use async_trait::async_trait;
	///
	/// #[derive(Clone, Default)]
	/// struct Config {
	///     value: String,
	/// }
	///
	/// # #[async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	///
	/// let config = Config { value: "test".to_string() };
	/// let depends = Depends::from_value(config);
	/// assert_eq!(depends.value, "test");
	/// ```
	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::{Depends, 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 depends = Depends::from_value(Config::default());
	/// let arc: &Arc<Config> = depends.as_arc();
	/// ```
	pub fn as_arc(&self) -> &Arc<T> {
		&self.inner
	}

	/// Get injection metadata
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Depends, 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 depends = Depends::from_value(Config::default());
	/// let metadata = depends.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`](Depends::into_inner), this method does **not** require
	/// `T: Clone`.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::Depends;
	///
	/// // Success: single owner
	/// let depends = Depends::from_value(42u32);
	/// let value = depends.try_unwrap().unwrap();
	/// assert_eq!(value, 42);
	///
	/// // Failure: multiple owners
	/// let depends = Depends::from_value(42u32);
	/// let _clone = depends.clone();
	/// let err = depends.try_unwrap().unwrap_err();
	/// assert_eq!(*err, 42); // still accessible via Deref
	/// ```
	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,
			}),
		}
	}
}

impl<T: Clone + Send + Sync + 'static> Depends<T> {
	/// Extract the inner value from the Depends wrapper.
	///
	/// This method tries to unwrap the Arc. If the Arc has multiple strong references,
	/// it clones the inner value instead.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Depends, Injectable, InjectionContext, DiResult};
	/// # use async_trait::async_trait;
	///
	/// #[derive(Clone, Default)]
	/// struct Config {
	///     value: String,
	/// }
	///
	/// # #[async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	///
	/// let config = Config { value: "test".to_string() };
	/// let depends = Depends::from_value(config);
	/// let inner = depends.into_inner();
	/// assert_eq!(inner.value, "test");
	/// ```
	pub fn into_inner(self) -> T {
		Arc::try_unwrap(self.inner).unwrap_or_else(|arc| (*arc).clone())
	}
}

/// Sugar for `Depends<Result<T, E>>` — commonly used with
/// `#[injectable_factory]` factories that return `Result<T, E>` to maintain
/// a distinct DI registry key from `T`.
///
/// # Example
///
/// ```rust
/// use reinhardt_di::{Depends, DependsResult};
///
/// struct User;
/// struct SessionError;
///
/// // Before: verbose inner type
/// let _session_user: Depends<Result<User, SessionError>>;
///
/// // After: sugar alias
/// let _session_user: DependsResult<User, SessionError>;
/// ```
pub type DependsResult<T, E> = Depends<Result<T, E>>;

/// Sugar for `Depends<Option<T>>` — used with `#[injectable_factory]`
/// factories that return `Option<T>` to represent an optionally-available
/// dependency with a distinct DI registry key from `T`.
///
/// # Example
///
/// ```rust
/// use reinhardt_di::{Depends, DependsOption};
///
/// struct CacheBackend;
///
/// // Before: verbose inner type
/// let _cache: Depends<Option<CacheBackend>>;
///
/// // After: sugar alias
/// let _cache: DependsOption<CacheBackend>;
/// ```
pub type DependsOption<T> = Depends<Option<T>>;

/// Builder for Depends to support FastAPI-style API.
pub struct DependsBuilder<T: Send + Sync + 'static> {
	use_cache: bool,
	_phantom: std::marker::PhantomData<T>,
}

impl<T: Send + Sync + 'static> DependsBuilder<T> {
	/// Resolve the dependency.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{Depends, InjectionContext, SingletonScope, Injectable, DiResult};
	/// # use async_trait::async_trait;
	/// use std::sync::Arc;
	///
	/// #[derive(Clone, Default)]
	/// struct Config {
	///     value: String,
	/// }
	///
	/// # #[async_trait]
	/// # impl Injectable for Config {
	/// #     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
	/// #         Ok(Config::default())
	/// #     }
	/// # }
	///
	/// # async fn example() -> DiResult<()> {
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	/// let builder = Depends::<Config>::builder();
	/// let result = builder.resolve(&ctx).await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn resolve(self, ctx: &InjectionContext) -> DiResult<Depends<T>>
	where
		T: Injectable,
	{
		Depends::resolve(ctx, self.use_cache).await
	}
}

impl<T: Send + Sync + 'static> Deref for Depends<T> {
	type Target = T;

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

impl<T: Send + Sync + 'static> Clone for Depends<T> {
	fn clone(&self) -> Self {
		Self {
			inner: Arc::clone(&self.inner),
			metadata: self.metadata,
		}
	}
}

impl<T: Send + Sync + 'static> AsRef<T> for Depends<T> {
	fn as_ref(&self) -> &T {
		&self.inner
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{DependencyScope as RegistryScope, SingletonScope, global_registry};
	use rstest::rstest;

	#[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(),
			})
		}
	}

	/// Register TestConfig in the global registry for resolution tests.
	fn register_test_config() {
		let registry = global_registry();
		if !registry.is_registered::<TestConfig>() {
			registry.register_async::<TestConfig, _, _>(RegistryScope::Request, |_ctx| async {
				Ok(TestConfig {
					value: "test".to_string(),
				})
			});
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_from_value() {
		// Arrange
		let config = TestConfig {
			value: "custom".to_string(),
		};

		// Act
		let depends = Depends::from_value(config);

		// Assert
		assert_eq!(depends.value, "custom");
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_into_inner() {
		// Arrange
		let config = TestConfig {
			value: "test".to_string(),
		};
		let depends = Depends::from_value(config);

		// Act
		let extracted = depends.into_inner();

		// Assert
		assert_eq!(extracted.value, "test");
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_clone() {
		// Arrange
		let config = TestConfig {
			value: "test".to_string(),
		};
		let depends1 = Depends::from_value(config);

		// Act
		let depends2 = depends1.clone();

		// Assert
		assert_eq!(depends1.value, "test");
		assert_eq!(depends2.value, "test");
		assert!(Arc::ptr_eq(depends1.as_arc(), depends2.as_arc()));
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_deref() {
		// Arrange
		let config = TestConfig {
			value: "test".to_string(),
		};
		let depends = Depends::from_value(config);

		// Act & Assert
		assert_eq!(depends.value, "test");
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_metadata() {
		// Arrange
		let config = TestConfig {
			value: "test".to_string(),
		};

		// Act
		let depends = Depends::from_value(config);

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

	#[rstest]
	#[tokio::test]
	async fn test_depends_as_arc() {
		// Arrange
		let config = TestConfig {
			value: "arc_test".to_string(),
		};
		let depends = Depends::from_value(config);

		// Act
		let arc = depends.as_arc();

		// Assert
		assert_eq!(arc.value, "arc_test");
		assert_eq!(Arc::strong_count(arc), 1);
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_as_ref() {
		// Arrange
		let config = TestConfig {
			value: "ref_test".to_string(),
		};
		let depends = Depends::from_value(config);

		// Act
		let reference: &TestConfig = depends.as_ref();

		// Assert
		assert_eq!(reference.value, "ref_test");
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_resolve_with_context() {
		// Arrange
		register_test_config();
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let depends = Depends::<TestConfig>::resolve(&ctx, true).await.unwrap();

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

	#[rstest]
	#[tokio::test]
	async fn test_depends_resolve_uncached() {
		// Arrange
		register_test_config();
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let depends = Depends::<TestConfig>::resolve(&ctx, false).await.unwrap();

		// Assert
		assert_eq!(depends.value, "test");
		assert!(!depends.metadata().cached);
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_builder_resolve() {
		// Arrange
		register_test_config();
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let depends = Depends::<TestConfig>::builder()
			.resolve(&ctx)
			.await
			.unwrap();

		// Assert
		assert_eq!(depends.value, "test");
		assert!(depends.metadata().cached);
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_builder_no_cache_resolve() {
		// Arrange
		register_test_config();
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let depends = Depends::<TestConfig>::builder_no_cache()
			.resolve(&ctx)
			.await
			.unwrap();

		// Assert
		assert_eq!(depends.value, "test");
		assert!(!depends.metadata().cached);
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_resolve_or_inject_failing_injectable_returns_error() {
		// Arrange: type whose inject() always fails and is not in the registry.
		// resolve_or_inject() falls back to T::inject() which returns an error.
		#[derive(Debug)]
		struct FailingType;

		#[async_trait::async_trait]
		impl Injectable for FailingType {
			async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
				Err(crate::DiError::NotRegistered {
					type_name: "FailingType".into(),
					hint: "intentionally failing".into(),
				})
			}
		}

		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let result = Depends::<FailingType>::resolve(&ctx, true).await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_resolve_from_registry_unregistered_type_returns_error() {
		// Arrange: type that is not in the registry.
		// resolve_from_registry() returns DependencyNotRegistered.
		#[derive(Debug)]
		struct UnregisteredType;

		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let result = Depends::<UnregisteredType>::resolve_from_registry(&ctx, true).await;

		// Assert
		assert!(result.is_err());
		assert!(matches!(
			result.unwrap_err(),
			DiError::DependencyNotRegistered { .. }
		),);
	}

	/// Factory-registered type can be resolved via `resolve_from_registry()`
	/// without an `Injectable` implementation. This is the core fix for #3515.
	#[rstest]
	#[tokio::test]
	async fn test_depends_resolve_from_registry_factory_type_without_injectable() {
		// Arrange: type registered via factory, no Injectable impl
		#[derive(Debug, Clone)]
		struct FactoryOnlyType {
			value: String,
		}

		let registry = global_registry();
		if !registry.is_registered::<FactoryOnlyType>() {
			registry.register_async::<FactoryOnlyType, _, _>(
				RegistryScope::Request,
				|_ctx| async {
					Ok(FactoryOnlyType {
						value: "from_factory".to_string(),
					})
				},
			);
		}

		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let depends = Depends::<FactoryOnlyType>::resolve_from_registry(&ctx, true)
			.await
			.unwrap();

		// Assert
		assert_eq!(depends.value, "from_factory");
	}

	/// Manual Injectable impl can be resolved via `resolve()` even when the
	/// type is not in the global registry (falls back to T::inject()).
	#[rstest]
	#[tokio::test]
	async fn test_depends_resolve_manual_injectable_fallback() {
		// Arrange: type with manual Injectable impl, not in registry
		#[derive(Debug, Clone)]
		struct ManualType {
			origin: String,
		}

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

		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let depends = Depends::<ManualType>::resolve(&ctx, true).await.unwrap();

		// Assert
		assert_eq!(depends.origin, "from_inject");
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_metadata_preserved_on_clone() {
		// Arrange
		let config = TestConfig {
			value: "metadata".to_string(),
		};
		let depends1 = Depends::from_value(config);

		// Act
		let depends2 = depends1.clone();

		// Assert
		assert_eq!(depends1.metadata().scope, depends2.metadata().scope);
		assert_eq!(depends1.metadata().cached, depends2.metadata().cached);
	}

	/// Non-Clone type can be used with `Depends<T>` via `from_value()`,
	/// `clone()` (Arc-based), `Deref`, and `AsRef`.
	/// `into_inner()` is NOT available for non-Clone types.
	#[rstest]
	#[tokio::test]
	async fn test_depends_non_clone_type() {
		// Arrange
		#[derive(Debug)]
		struct NonCloneService {
			id: u32,
		}

		let service = NonCloneService { id: 42 };

		// Act
		let depends = Depends::from_value(service);
		let cloned_depends = depends.clone();

		// Assert
		assert_eq!(depends.id, 42);
		assert_eq!(cloned_depends.id, 42);
		assert!(Arc::ptr_eq(depends.as_arc(), cloned_depends.as_arc()));
		assert_eq!(depends.as_ref().id, 42);
	}

	/// Non-Clone type can be resolved via the global registry.
	#[rstest]
	#[tokio::test]
	async fn test_depends_non_clone_type_resolve() {
		// Arrange
		#[derive(Debug)]
		struct NonCloneRouter {
			prefix: String,
		}

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

		let registry = global_registry();
		if !registry.is_registered::<NonCloneRouter>() {
			registry.register_async::<NonCloneRouter, _, _>(RegistryScope::Request, |_ctx| async {
				Ok(NonCloneRouter {
					prefix: "/api".to_string(),
				})
			});
		}

		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Act
		let depends = Depends::<NonCloneRouter>::resolve(&ctx, true)
			.await
			.unwrap();

		// Assert
		assert_eq!(depends.prefix, "/api");
		assert!(depends.metadata().cached);
	}

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

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

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

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

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

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

	/// `try_unwrap()` works with non-Clone types (the primary use case).
	#[rstest]
	#[tokio::test]
	async fn test_depends_try_unwrap_non_clone_type() {
		// Arrange
		#[derive(Debug, PartialEq)]
		struct NonCloneRouter {
			prefix: String,
		}

		let router = NonCloneRouter {
			prefix: "/api".to_string(),
		};
		let depends = Depends::from_value(router);

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

		// Assert
		assert_eq!(
			result.unwrap(),
			NonCloneRouter {
				prefix: "/api".to_string()
			}
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_result_type_alias_ok_variant() {
		// Arrange
		let ok_value: Result<String, String> = Ok("success".to_string());

		// Act
		let depends: DependsResult<String, String> = Depends::from_value(ok_value);

		// Assert
		assert!(depends.is_ok());
		assert_eq!(depends.as_ref().as_ref().unwrap(), "success");
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_result_type_alias_err_variant() {
		// Arrange
		let err_value: Result<String, String> = Err("failure".to_string());

		// Act
		let depends: DependsResult<String, String> = Depends::from_value(err_value);

		// Assert
		assert!(depends.is_err());
		assert_eq!(depends.as_ref().as_ref().unwrap_err(), "failure");
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_option_type_alias_some_variant() {
		// Arrange
		let some_value: Option<String> = Some("present".to_string());

		// Act
		let depends: DependsOption<String> = Depends::from_value(some_value);

		// Assert
		assert!(depends.is_some());
		assert_eq!(depends.as_ref().as_ref().unwrap(), "present");
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_option_type_alias_none_variant() {
		// Arrange
		let none_value: Option<String> = None;

		// Act
		let depends: DependsOption<String> = Depends::from_value(none_value);

		// Assert
		assert!(depends.is_none());
	}
}