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
//! Injection context for dependency resolution

use crate::function_handle::FunctionHandle;
use crate::override_registry::OverrideRegistry;
use crate::scope::{RequestScope, SingletonScope};
use reinhardt_http::Request as HttpRequest;
use std::any::Any;
use std::sync::Arc;

// Re-export ParamContext and Request types for convenience
#[cfg(feature = "params")]
pub use crate::params::{ParamContext, Request};

/// The main injection context for dependency resolution.
///
/// `InjectionContext` manages both request-scoped and singleton-scoped dependencies,
/// as well as dependency overrides for testing.
///
/// # Override Support
///
/// The context supports dependency overrides, which take precedence over normal
/// dependency resolution. This is particularly useful for testing:
///
/// ```rust,no_run
/// use reinhardt_di::{InjectionContext, SingletonScope};
/// use std::sync::Arc;
///
/// # #[derive(Clone)]
/// # struct Database;
/// # impl Database {
/// #     fn connect(_url: &str) -> Self { Database }
/// #     fn mock() -> Self { Database }
/// # }
/// # fn create_database() -> Database { Database::connect("production://db") }
///
/// let singleton = Arc::new(SingletonScope::new());
/// let ctx = InjectionContext::builder(singleton).build();
///
/// // Set override for testing
/// ctx.dependency(create_database).override_with(Database::mock());
/// ```
pub struct InjectionContext {
	request_scope: RequestScope,
	singleton_scope: Arc<SingletonScope>,
	/// Override registry for dependency substitution (e.g., for testing)
	override_registry: Arc<OverrideRegistry>,
	/// Per-context dependency registry that takes precedence over the global
	/// registry during resolution. When `Some`, types registered here are
	/// resolved first; types not found fall back to `global_registry()`.
	registry: Option<Arc<crate::registry::DependencyRegistry>>,
	/// HTTP request for parameter extraction
	#[cfg(feature = "params")]
	request: Option<Arc<Request>>,
	/// Parameter context for path/header/cookie extraction
	#[cfg(feature = "params")]
	param_context: Option<Arc<ParamContext>>,
}

/// Builder for constructing `InjectionContext` instances.
///
/// Provides a fluent API for building injection contexts with optional HTTP request support.
///
/// # Examples
///
/// ```
/// use reinhardt_di::{InjectionContext, SingletonScope};
///
/// let singleton_scope = SingletonScope::new();
/// let ctx = InjectionContext::builder(singleton_scope).build();
/// ```
pub struct InjectionContextBuilder {
	singleton_scope: Arc<SingletonScope>,
	registry: Option<Arc<crate::registry::DependencyRegistry>>,
	#[cfg(feature = "params")]
	request: Option<Request>,
	#[cfg(feature = "params")]
	param_context: Option<ParamContext>,
}

impl InjectionContextBuilder {
	/// Set the HTTP request for this context.
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_di::{InjectionContext, SingletonScope, Request};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let request = Request::builder()
	///     .method(hyper::Method::GET)
	///     .uri("/")
	///     .build()
	///     .unwrap();
	///
	/// let ctx = InjectionContext::builder(singleton_scope)
	///     .with_request(request)
	///     .build();
	/// ```
	#[cfg(feature = "params")]
	pub fn with_request(mut self, request: Request) -> Self {
		self.request = Some(request);
		self
	}

	/// Set the parameter context for this context.
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_di::{InjectionContext, SingletonScope, ParamContext};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let param_context = ParamContext::new();
	///
	/// let ctx = InjectionContext::builder(singleton_scope)
	///     .with_param_context(param_context)
	///     .build();
	/// ```
	#[cfg(feature = "params")]
	pub fn with_param_context(mut self, param_context: ParamContext) -> Self {
		self.param_context = Some(param_context);
		self
	}

	/// Attach a per-context dependency registry.
	///
	/// Types registered in this registry take precedence over the global
	/// registry during [`InjectionContext::resolve`]. Types not found here
	/// fall back to `global_registry()`.
	pub fn with_registry(mut self, registry: Arc<crate::registry::DependencyRegistry>) -> Self {
		self.registry = Some(registry);
		self
	}

	/// Register a singleton instance in the context.
	///
	/// This allows explicit registration of pre-configured instances
	/// that will be shared across all requests.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	/// use std::sync::Arc;
	///
	/// #[derive(Debug, Clone)]
	/// struct DatabaseConfig {
	///     url: String,
	/// }
	///
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let config = DatabaseConfig { url: "postgres://localhost".to_string() };
	///
	/// let ctx = InjectionContext::builder(singleton_scope)
	///     .singleton(config)
	///     .build();
	/// ```
	pub fn singleton<T: std::any::Any + Send + Sync>(self, instance: T) -> Self {
		self.singleton_scope.set(instance);
		self
	}

	/// Build the final `InjectionContext` instance.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	/// ```
	pub fn build(self) -> InjectionContext {
		InjectionContext {
			request_scope: RequestScope::new(),
			singleton_scope: self.singleton_scope,
			override_registry: Arc::new(OverrideRegistry::new()),
			registry: self.registry,
			#[cfg(feature = "params")]
			request: self.request.map(Arc::new),
			#[cfg(feature = "params")]
			param_context: self.param_context.map(Arc::new),
		}
	}
}

impl Clone for InjectionContext {
	fn clone(&self) -> Self {
		Self {
			request_scope: self.request_scope.deep_clone(),
			singleton_scope: Arc::clone(&self.singleton_scope),
			override_registry: Arc::clone(&self.override_registry),
			registry: self.registry.clone(),
			#[cfg(feature = "params")]
			request: self.request.clone(),
			#[cfg(feature = "params")]
			param_context: self.param_context.clone(),
		}
	}
}

impl InjectionContext {
	/// Create a new `InjectionContextBuilder`.
	///
	/// This is the recommended way to construct an `InjectionContext`.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	/// ```
	pub fn builder(singleton_scope: impl Into<Arc<SingletonScope>>) -> InjectionContextBuilder {
		InjectionContextBuilder {
			singleton_scope: singleton_scope.into(),
			registry: None,
			#[cfg(feature = "params")]
			request: None,
			#[cfg(feature = "params")]
			param_context: None,
		}
	}

	/// Gets the HTTP request from the context.
	///
	/// Returns `None` if no request was set (e.g., when testing without HTTP context).
	/// Returns a reference to the request.
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_di::{InjectionContext, SingletonScope, Request, ParamContext};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let request = Request::builder()
	///     .method(hyper::Method::GET)
	///     .uri("/")
	///     .build()
	///     .unwrap();
	/// let param_context = ParamContext::new();
	///
	/// let ctx = InjectionContext::builder(singleton_scope)
	///     .with_request(request)
	///     .with_param_context(param_context)
	///     .build();
	///
	/// assert!(ctx.get_http_request().is_some());
	/// ```
	#[cfg(feature = "params")]
	pub fn get_http_request(&self) -> Option<&Request> {
		self.request.as_ref().map(|arc| arc.as_ref())
	}

	/// Gets the parameter context from the context.
	///
	/// Returns `None` if no parameter context was set.
	/// Returns a reference to the parameter context.
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_di::{InjectionContext, SingletonScope, Request, ParamContext};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let request = Request::builder()
	///     .method(hyper::Method::GET)
	///     .uri("/")
	///     .build()
	///     .unwrap();
	/// let param_context = ParamContext::new();
	///
	/// let ctx = InjectionContext::builder(singleton_scope)
	///     .with_request(request)
	///     .with_param_context(param_context)
	///     .build();
	///
	/// assert!(ctx.get_param_context().is_some());
	/// ```
	#[cfg(feature = "params")]
	pub fn get_param_context(&self) -> Option<&ParamContext> {
		self.param_context.as_ref().map(|arc| arc.as_ref())
	}

	/// Sets the HTTP request and parameter context.
	///
	/// This can be used to add HTTP context to an existing InjectionContext.
	/// The request and parameter context will be wrapped in Arc internally.
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_di::{InjectionContext, SingletonScope, Request, ParamContext};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let mut ctx = InjectionContext::builder(singleton_scope).build();
	///
	/// let request = Request::builder()
	///     .method(hyper::Method::GET)
	///     .uri("/")
	///     .build()
	///     .unwrap();
	/// let param_context = ParamContext::new();
	///
	/// ctx.set_http_request(request, param_context);
	/// ```
	#[cfg(feature = "params")]
	pub fn set_http_request(&mut self, request: Request, param_context: ParamContext) {
		self.request = Some(Arc::new(request));
		self.param_context = Some(Arc::new(param_context));
	}
	/// Retrieves a request-scoped value from the context.
	///
	/// Request-scoped values are cached only for the duration of a single request.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	/// use std::sync::Arc;
	///
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	///
	/// ctx.set_request(42i32);
	/// let value = ctx.get_request::<i32>().unwrap();
	/// assert_eq!(*value, 42);
	/// ```
	pub fn get_request<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
		self.request_scope.get::<T>()
	}
	/// Stores a value in the request scope.
	///
	/// The value is cached for the duration of the current request only.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	/// use std::sync::Arc;
	///
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	///
	/// ctx.set_request("request-data".to_string());
	/// assert!(ctx.get_request::<String>().is_some());
	/// ```
	pub fn set_request<T: Any + Send + Sync>(&self, value: T) {
		self.request_scope.set(value);
	}

	/// Stores a pre-wrapped `Arc<T>` in the request scope.
	///
	/// This avoids the need to unwrap and re-wrap Arc values that are
	/// already in Arc form, such as those returned by factory functions.
	pub(crate) fn set_request_arc<T: Any + Send + Sync>(&self, value: Arc<T>) {
		self.request_scope.set_arc(value);
	}
	/// Retrieves a singleton value from the context.
	///
	/// Singleton values persist across all requests and are shared application-wide.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	/// use std::sync::Arc;
	///
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// singleton_scope.set(100u64);
	///
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	/// let value = ctx.get_singleton::<u64>().unwrap();
	/// assert_eq!(*value, 100);
	/// ```
	pub fn get_singleton<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
		self.singleton_scope.get::<T>()
	}
	/// Stores a value in the singleton scope.
	///
	/// The value persists across all requests and is shared application-wide.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	/// use std::sync::Arc;
	///
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	///
	/// ctx.set_singleton("global-config".to_string());
	/// assert!(ctx.get_singleton::<String>().is_some());
	/// ```
	pub fn set_singleton<T: Any + Send + Sync>(&self, value: T) {
		self.singleton_scope.set(value);
	}

	/// Stores a pre-wrapped `Arc<T>` in the singleton scope.
	///
	/// This avoids the need to unwrap and re-wrap Arc values that are
	/// already in Arc form, such as those returned by factory functions.
	fn set_singleton_arc<T: Any + Send + Sync>(&self, value: Arc<T>) {
		self.singleton_scope.set_arc(value);
	}

	/// Returns a reference to the singleton scope.
	///
	/// This is useful for advanced scenarios where direct access to the
	/// singleton scope is needed.
	pub fn singleton_scope(&self) -> &Arc<SingletonScope> {
		&self.singleton_scope
	}

	/// Internal helper for creating forked contexts.
	///
	/// Centralizes the construction logic shared between `fork()` and
	/// `fork_for_request()` to prevent field-drift when new fields are added.
	fn fork_inner(
		&self,
		#[cfg(feature = "params")] request: Option<Arc<HttpRequest>>,
		#[cfg(feature = "params")] param_context: Option<Arc<ParamContext>>,
	) -> InjectionContext {
		InjectionContext {
			request_scope: RequestScope::new(),
			singleton_scope: self.singleton_scope.clone(),
			override_registry: self.override_registry.clone(),
			registry: self.registry.clone(),
			#[cfg(feature = "params")]
			request,
			#[cfg(feature = "params")]
			param_context,
		}
	}

	/// Creates a per-request fork of this context with an HTTP request.
	///
	/// The forked context shares the same singleton scope but has a fresh
	/// request scope. When the `params` feature is enabled, the HTTP request
	/// and its path parameters are made available for parameter extraction.
	///
	/// The HTTP request is stored in both the dedicated `request` field
	/// (for [`get_http_request()`](Self::get_http_request)) and the
	/// `request_scope` (for [`get_request::<HttpRequest>()`](Self::get_request)),
	/// ensuring that `Injectable` types such as `ServerFnRequest` can
	/// retrieve it via either accessor.
	pub fn fork_for_request(&self, request: HttpRequest) -> InjectionContext {
		let request_arc = Arc::new(request);

		#[cfg(feature = "params")]
		let param_context = Some(Arc::new(ParamContext::with_path_params(
			request_arc.path_params.clone(),
		)));

		let ctx = self.fork_inner(
			#[cfg(feature = "params")]
			Some(Arc::clone(&request_arc)),
			#[cfg(feature = "params")]
			param_context,
		);

		// Also register in request_scope so that Injectable types
		// (e.g. ServerFnRequest, ServerFnBody) can retrieve it via
		// get_request::<HttpRequest>()
		ctx.set_request_arc(request_arc);

		ctx
	}

	/// Creates a per-request fork of this context without an HTTP request.
	///
	/// The forked context shares the same singleton scope but has a fresh
	/// request scope. Unlike `fork_for_request`, this method does not store
	/// an HTTP request, so path parameter extraction is not available.
	///
	/// This is intended for non-HTTP protocols (gRPC, GraphQL) where
	/// request-scoped isolation is needed but HTTP request data is not available.
	pub fn fork(&self) -> InjectionContext {
		self.fork_inner(
			#[cfg(feature = "params")]
			None,
			#[cfg(feature = "params")]
			None,
		)
	}

	/// Returns a reference to the override registry.
	///
	/// The override registry stores function-level overrides that take
	/// precedence over normal dependency resolution.
	pub fn overrides(&self) -> &OverrideRegistry {
		&self.override_registry
	}

	/// Creates a handle for the given injectable function.
	///
	/// This method provides a fluent API for setting and managing dependency
	/// overrides. The function pointer is used as a unique key to identify
	/// which injectable function should be overridden.
	///
	/// # Note
	///
	/// This method is designed to work with functions annotated with `#[injectable]`.
	/// The `#[injectable]` macro generates a 0-argument function regardless of
	/// the original function's parameter count, as all `#[inject]` parameters
	/// are resolved internally by the DI system.
	///
	/// # Type Parameters
	///
	/// * `O` - The output type of the function (the dependency type)
	///
	/// # Arguments
	///
	/// * `func` - A function pointer to the injectable function
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	/// use std::sync::Arc;
	///
	/// # #[derive(Clone)]
	/// # struct Database;
	/// # impl Database {
	/// #     fn connect(_url: &str) -> Self { Database }
	/// #     fn mock() -> Self { Database }
	/// # }
	/// # struct Config { url: String }
	/// # fn create_database() -> Database {
	/// #     Database::connect("production://db")
	/// # }
	///
	/// let singleton = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton).build();
	///
	/// // Set override - create_database is 0-argument after macro expansion
	/// ctx.dependency(create_database).override_with(Database::mock());
	///
	/// // Check if override exists
	/// assert!(ctx.dependency(create_database).has_override());
	///
	/// // Clear override
	/// ctx.dependency(create_database).clear_override();
	/// ```
	pub fn dependency<O>(&self, func: fn() -> O) -> FunctionHandle<'_, O>
	where
		O: Clone + Send + Sync + 'static,
	{
		let func_ptr = func as usize;
		FunctionHandle::new(self, func_ptr)
	}

	/// Gets an override value for a function pointer.
	///
	/// This is primarily used internally by the `#[injectable]` macro to check
	/// for overrides before executing the actual function.
	///
	/// # Arguments
	///
	/// * `func_ptr` - The function pointer address as usize
	///
	/// # Returns
	///
	/// `Some(value)` if an override is set, `None` otherwise.
	pub fn get_override<O: Clone + 'static>(&self, func_ptr: usize) -> Option<O> {
		self.override_registry.get(func_ptr)
	}

	/// Clears all overrides from the context.
	///
	/// This is useful for cleanup in tests to ensure a clean state.
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	/// use std::sync::Arc;
	///
	/// fn my_factory() -> i32 { 42 }
	///
	/// let singleton = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton).build();
	///
	/// ctx.dependency(my_factory).override_with(100);
	/// assert!(ctx.dependency(my_factory).has_override());
	///
	/// ctx.clear_overrides();
	/// assert!(!ctx.dependency(my_factory).has_override());
	/// ```
	pub fn clear_overrides(&self) {
		self.override_registry.clear();
	}

	/// Layered registry lookup: per-context registry takes precedence, then
	/// global. Returns the scope and which registry owns the type.
	fn find_type_registration<T: Any + Send + Sync + 'static>(
		&self,
	) -> Option<(
		crate::registry::DependencyScope,
		&Arc<crate::registry::DependencyRegistry>,
	)> {
		use crate::registry::global_registry;

		if let Some(ref reg) = self.registry
			&& let Some(scope) = reg.get_scope::<T>()
		{
			return Some((scope, reg));
		}
		let global = global_registry();
		global.get_scope::<T>().map(|scope| (scope, global))
	}

	/// Resolve a dependency by type.
	///
	/// Resolution checks the per-context registry first (if set via
	/// [`InjectionContextBuilder::with_registry`]), then falls back to the
	/// global registry. Scope caches (singleton / request) are consulted
	/// before invoking the factory.
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_di::{InjectionContext, SingletonScope};
	/// use std::sync::Arc;
	/// # use async_trait::async_trait;
	///
	/// # #[derive(Clone)]
	/// # struct Config;
	/// # #[async_trait]
	/// # impl reinhardt_di::Injectable for Config {
	/// #     async fn inject(_ctx: &InjectionContext) -> reinhardt_di::DiResult<Self> {
	/// #         Ok(Config)
	/// #     }
	/// # }
	/// # async fn example() -> reinhardt_di::DiResult<()> {
	/// let singleton_scope = Arc::new(SingletonScope::new());
	/// let ctx = InjectionContext::builder(singleton_scope).build();
	///
	/// let config = ctx.resolve::<Config>().await?;
	/// # Ok(())
	/// # }
	/// ```
	pub async fn resolve<T: Any + Send + Sync + 'static>(&self) -> crate::DiResult<Arc<T>> {
		use crate::cycle_detection::{
			begin_scoped_resolution, current_dependent_scope, current_dependent_type_name,
			register_type_name, with_cycle_detection_scope,
		};
		use crate::registry::DependencyScope;

		with_cycle_detection_scope(async {
			let type_id = std::any::TypeId::of::<T>();
			let type_name = std::any::type_name::<T>();

			// Register type name (for error messages)
			register_type_name::<T>(type_name);

			// [Fast path] Skip circular detection on cache hit
			let (scope, registry) = match self.find_type_registration::<T>() {
				Some(entry) => entry,
				None => {
					// Fallback: check scope caches for types pre-seeded via
					// SingletonScope::set() / InjectionContext::set_request()
					// (e.g., types registered through DiRegistrationList).
					// Singleton pre-seeds are safe for any dependent scope.
					if let Some(cached) = self.get_singleton::<T>() {
						return Ok(cached);
					}
					// Request pre-seeds are request-scoped: apply the same
					// hierarchy check as registry-registered types.
					if let Some(cached) = self.get_request::<T>() {
						if !DependencyScope::Request.outlives(current_dependent_scope()) {
							return Err(crate::DiError::ScopeError(format!(
								"Scope violation: {:?}-scoped '{}' cannot resolve \
								 Request-scoped '{}' (pre-seeded); the dependency would \
								 be captured with a shorter lifetime",
								current_dependent_scope(),
								current_dependent_type_name(),
								type_name,
							)));
						}
						return Ok(cached);
					}
					return Err(crate::DiError::DependencyNotRegistered {
						type_name: type_name.to_string(),
					});
				}
			};

			// Scope hierarchy check — runs on EVERY resolution (cache hit or miss).
			// A singleton dependent must not resolve a request-scoped dependency,
			// even if that dependency is already cached from a prior request.
			if !scope.outlives(current_dependent_scope()) {
				return Err(crate::DiError::ScopeError(format!(
					"Scope violation: {:?}-scoped '{}' cannot resolve \
					 {:?}-scoped '{}'; the dependency would be captured with \
					 a shorter lifetime",
					current_dependent_scope(),
					current_dependent_type_name(),
					scope,
					type_name,
				)));
			}

			match scope {
				DependencyScope::Singleton => {
					if let Some(cached) = self.get_singleton::<T>() {
						return Ok(cached); // < 5% overhead
					}
				}
				DependencyScope::Request => {
					if let Some(cached) = self.get_request::<T>() {
						return Ok(cached); // < 5% overhead
					}
				}
				_ => {}
			}

			// [Slow path] Scope-aware resolution with cycle detection
			let _guard =
				begin_scoped_resolution(type_id, type_name, scope).map_err(|e| match e {
					crate::cycle_detection::CycleError::ScopeViolation { .. } => {
						crate::DiError::ScopeError(e.to_string())
					}
					other => crate::DiError::CircularDependency(other.to_string()),
				})?;

			// Actual resolution processing (existing logic)
			self.resolve_internal::<T>(scope, registry).await
			// Guard is automatically cleaned up when dropped
		})
		.await
	}

	/// Resolve a type from the registry, bypassing cycle detection.
	///
	/// Used by the `Injectable` impl generated by `#[injectable_factory]`.
	/// The caller (`Depends::resolve`) has already registered the type in the
	/// cycle detection stack, so a second `begin_resolution` for the same type
	/// would trigger a false circular dependency error.
	///
	/// This method performs cache lookup and delegates to `resolve_internal`
	/// without adding a cycle detection guard.
	#[doc(hidden)]
	pub async fn __resolve_from_registry<T: Any + Send + Sync + 'static>(
		&self,
	) -> crate::DiResult<Arc<T>> {
		use crate::cycle_detection::{current_dependent_scope, current_dependent_type_name};
		use crate::registry::DependencyScope;

		let type_name = std::any::type_name::<T>();
		let (scope, registry) = match self.find_type_registration::<T>() {
			Some(entry) => entry,
			None => {
				// Fallback: check scope caches for pre-seeded types
				if let Some(cached) = self.get_singleton::<T>() {
					return Ok(cached);
				}
				if let Some(cached) = self.get_request::<T>() {
					if !DependencyScope::Request.outlives(current_dependent_scope()) {
						return Err(crate::DiError::ScopeError(format!(
							"Scope violation: {:?}-scoped '{}' cannot resolve \
							 Request-scoped '{}' (pre-seeded); the dependency would \
							 be captured with a shorter lifetime",
							current_dependent_scope(),
							current_dependent_type_name(),
							type_name,
						)));
					}
					return Ok(cached);
				}
				return Err(crate::DiError::DependencyNotRegistered {
					type_name: type_name.to_string(),
				});
			}
		};

		// Scope hierarchy check — same as resolve()
		if !scope.outlives(current_dependent_scope()) {
			return Err(crate::DiError::ScopeError(format!(
				"Scope violation: {:?}-scoped '{}' cannot resolve \
				 {:?}-scoped '{}'; the dependency would be captured with \
				 a shorter lifetime",
				current_dependent_scope(),
				current_dependent_type_name(),
				scope,
				type_name,
			)));
		}

		// Fast cache check (same as resolve)
		match scope {
			DependencyScope::Singleton => {
				if let Some(cached) = self.get_singleton::<T>() {
					return Ok(cached);
				}
			}
			DependencyScope::Request => {
				if let Some(cached) = self.get_request::<T>() {
					return Ok(cached);
				}
			}
			_ => {}
		}

		self.resolve_internal::<T>(scope, registry).await
	}

	async fn resolve_internal<T: Any + Send + Sync + 'static>(
		&self,
		scope: crate::registry::DependencyScope,
		registry: &Arc<crate::registry::DependencyRegistry>,
	) -> crate::DiResult<Arc<T>> {
		use crate::registry::DependencyScope;

		match scope {
			DependencyScope::Singleton => {
				// Create new instance
				let instance = registry.create::<T>(self).await?;

				// Cache the Arc directly in singleton scope without unwrapping.
				// This avoids panics when the factory retains an Arc clone,
				// which causes Arc::try_unwrap to fail.
				self.set_singleton_arc(Arc::clone(&instance));
				Ok(instance)
			}
			DependencyScope::Request => {
				// Create new instance
				let instance = registry.create::<T>(self).await?;

				// Cache the Arc directly in request scope without unwrapping.
				// This avoids panics when the factory retains an Arc clone.
				self.set_request_arc(Arc::clone(&instance));
				Ok(instance)
			}
			DependencyScope::Transient => {
				// Never cache, always create new
				registry.create::<T>(self).await
			}
		}
	}
}

/// Context for per-request dependency injection resolution.
///
/// Wraps an `InjectionContext` with request-scoped lifetime management.
pub struct RequestContext {
	injection_ctx: InjectionContext,
}

impl RequestContext {
	/// Creates a new RequestContext with a shared singleton scope.
	///
	/// This is typically used to create a context for each incoming request.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{RequestContext, SingletonScope};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let request_ctx = RequestContext::new(singleton_scope);
	/// ```
	pub fn new(singleton_scope: SingletonScope) -> Self {
		Self {
			injection_ctx: InjectionContext::builder(singleton_scope).build(),
		}
	}
	/// Returns a reference to the underlying injection context.
	///
	/// This allows access to the dependency injection context for resolving dependencies.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::{RequestContext, SingletonScope};
	///
	/// let singleton_scope = SingletonScope::new();
	/// let request_ctx = RequestContext::new(singleton_scope);
	///
	/// let ctx = request_ctx.injection_context();
	/// ctx.set_request(42i32);
	/// ```
	pub fn injection_context(&self) -> &InjectionContext {
		&self.injection_ctx
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;

	#[rstest]
	fn test_fork_for_request_shares_singleton_scope() {
		// Arrange
		let singleton_scope = Arc::new(SingletonScope::new());
		singleton_scope.set(42u32);
		let ctx = InjectionContext::builder(singleton_scope).build();

		let request = HttpRequest::builder()
			.method(hyper::Method::GET)
			.uri("/test")
			.build()
			.unwrap();

		// Act
		let forked = ctx.fork_for_request(request);

		// Assert - singleton scope is shared
		let value = forked.get_singleton::<u32>();
		assert_eq!(value.map(|v| *v), Some(42));
	}

	#[rstest]
	fn test_fork_for_request_has_independent_request_scope() {
		// Arrange
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();
		ctx.set_request("original".to_string());

		let request = HttpRequest::builder()
			.method(hyper::Method::GET)
			.uri("/test")
			.build()
			.unwrap();

		// Act
		let forked = ctx.fork_for_request(request);

		// Assert - request scope is independent (not inherited)
		assert!(forked.get_request::<String>().is_none());
	}

	#[cfg(feature = "params")]
	#[rstest]
	fn test_fork_for_request_sets_http_request() {
		// Arrange
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		let request = HttpRequest::builder()
			.method(hyper::Method::POST)
			.uri("/api/users")
			.build()
			.unwrap();

		// Act
		let forked = ctx.fork_for_request(request);

		// Assert - HTTP request is available
		let http_req = forked.get_http_request();
		assert!(http_req.is_some());
		assert_eq!(http_req.unwrap().method, hyper::Method::POST);
	}

	#[rstest]
	fn test_fork_for_request_registers_http_request_in_request_scope() {
		// Arrange
		let singleton_scope = Arc::new(SingletonScope::new());
		let ctx = InjectionContext::builder(singleton_scope).build();

		let request = HttpRequest::builder()
			.method(hyper::Method::POST)
			.uri("/admin/api/server_fn/get_dashboard")
			.build()
			.unwrap();

		// Act
		let forked = ctx.fork_for_request(request);

		// Assert - HTTP request is retrievable via get_request::<HttpRequest>()
		// This is the accessor used by Injectable types like ServerFnRequest
		let req_from_scope: Option<Arc<HttpRequest>> = forked.get_request();
		assert!(req_from_scope.is_some());
		let req = req_from_scope.unwrap();
		assert_eq!(req.method, hyper::Method::POST);
		assert_eq!(req.uri.path(), "/admin/api/server_fn/get_dashboard");
	}
}