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
//! Global dependency registry for FastAPI-style dependency injection
//!
//! This module provides a global registry that stores factory functions for creating
//! dependencies. It uses the `inventory` crate to collect registrations at compile time
//! and build a runtime registry that can be queried by type.

use crate::{DiResult, Injectable, InjectionContext};
use async_trait::async_trait;
use dashmap::DashMap;
use std::any::{Any, TypeId};
use std::future::Future;
use std::marker::PhantomData;
use std::sync::{Arc, OnceLock};

/// Scope for dependency injection
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DependencyScope {
	/// Single instance shared across the entire application
	#[default]
	Singleton,
	/// New instance per request, cached within the request
	Request,
	/// New instance every time, never cached
	Transient,
}

impl DependencyScope {
	/// Returns `true` if a type at scope `self` (the dependency being resolved)
	/// lives at least as long as a type at scope `dependent` (the type
	/// requesting resolution).
	///
	/// The only prohibited combination is a `Singleton`-scoped dependent
	/// resolving a `Request`-scoped dependency, because the singleton would
	/// capture a stale, request-bound value for the entire process lifetime.
	pub fn outlives(&self, dependent: DependencyScope) -> bool {
		!matches!(
			(dependent, *self),
			(DependencyScope::Singleton, DependencyScope::Request)
		)
	}
}

/// Factory trait for creating dependencies
///
/// Factories are async functions that can resolve dependencies from an InjectionContext
/// and return a type-erased `Arc<dyn Any>`.
#[async_trait]
pub trait FactoryTrait: Send + Sync {
	/// Create an instance of the dependency
	async fn create(&self, ctx: &InjectionContext) -> DiResult<Arc<dyn Any + Send + Sync>>;
}

/// Wrapper for async factory functions
pub struct AsyncFactory<F, Fut, T>
where
	F: Fn(Arc<InjectionContext>) -> Fut + Send + Sync,
	Fut: Future<Output = DiResult<T>> + Send,
	T: Any + Send + Sync + 'static,
{
	factory: F,
	_phantom: std::marker::PhantomData<fn() -> (Fut, T)>,
}

impl<F, Fut, T> AsyncFactory<F, Fut, T>
where
	F: Fn(Arc<InjectionContext>) -> Fut + Send + Sync,
	Fut: Future<Output = DiResult<T>> + Send,
	T: Any + Send + Sync + 'static,
{
	/// Creates a new async factory from the given closure.
	pub fn new(factory: F) -> Self {
		Self {
			factory,
			_phantom: std::marker::PhantomData,
		}
	}
}

#[async_trait]
impl<F, Fut, T> FactoryTrait for AsyncFactory<F, Fut, T>
where
	F: Fn(Arc<InjectionContext>) -> Fut + Send + Sync,
	Fut: Future<Output = DiResult<T>> + Send + 'static,
	T: Any + Send + Sync + 'static,
{
	async fn create(&self, ctx: &InjectionContext) -> DiResult<Arc<dyn Any + Send + Sync>> {
		let ctx_arc = Arc::new(ctx.clone());
		let instance = (self.factory)(ctx_arc).await?;
		Ok(Arc::new(instance))
	}
}

/// Factory that creates instances via the `Injectable` trait.
///
/// Bypasses `AsyncFactory`'s `Fut: Sync` bound by implementing `FactoryTrait`
/// directly. This is necessary because `Injectable::inject` uses `async_trait`,
/// which returns `Pin<Box<dyn Future + Send>>` (not `Sync`).
pub struct InjectableFactory<T>(PhantomData<T>);

impl<T> Default for InjectableFactory<T> {
	fn default() -> Self {
		Self(PhantomData)
	}
}

impl<T> InjectableFactory<T> {
	/// Create a new `InjectableFactory`.
	pub fn new() -> Self {
		Self::default()
	}
}

#[async_trait]
impl<T: Injectable + Any + Send + Sync + 'static> FactoryTrait for InjectableFactory<T> {
	async fn create(&self, ctx: &InjectionContext) -> DiResult<Arc<dyn Any + Send + Sync>> {
		// Set task-local resolve context for get_di_context() access.
		// Since we only have &InjectionContext, clone into Arc (same pattern as AsyncFactory).
		let ctx_arc = Arc::new(ctx.clone());
		let resolve_ctx = crate::resolve_context::ResolveContext {
			root: crate::resolve_context::RESOLVE_CTX
				.try_with(|outer| Arc::clone(&outer.root))
				.unwrap_or_else(|_| Arc::clone(&ctx_arc)),
			current: Arc::clone(&ctx_arc),
		};

		let value = crate::resolve_context::RESOLVE_CTX
			.scope(resolve_ctx, T::inject(ctx))
			.await?;
		Ok(Arc::new(value))
	}
}

/// Type-erased factory function
type BoxedFactory = Box<dyn FactoryTrait>;

/// Global dependency registry
///
/// Stores factory functions for each type, along with their scope information.
/// Uses DashMap for thread-safe concurrent access without blocking.
pub struct DependencyRegistry {
	factories: DashMap<TypeId, BoxedFactory>,
	scopes: DashMap<TypeId, DependencyScope>,
	/// Maps type ID to its direct dependencies
	dependencies: DashMap<TypeId, Vec<TypeId>>,
	/// Maps type ID to its type name for debugging
	type_names: DashMap<TypeId, &'static str>,
	/// Maps type ID to its fully-qualified type name from `std::any::type_name`.
	/// Used for framework type detection (pseudo orphan rule).
	qualified_type_names: DashMap<TypeId, &'static str>,
}

impl DependencyRegistry {
	/// Create a new empty registry
	pub fn new() -> Self {
		Self {
			factories: DashMap::new(),
			scopes: DashMap::new(),
			dependencies: DashMap::new(),
			type_names: DashMap::new(),
			qualified_type_names: DashMap::new(),
		}
	}

	/// Register a factory for a type.
	///
	/// # Panics
	///
	/// Panics if a factory for the same `TypeId` is already registered.
	/// This prevents silent overwrites that lead to non-deterministic behavior
	/// when multiple `#[injectable_factory]` or `#[injectable]` macros produce
	/// the same return type. See [#3457].
	///
	/// To check before registering (e.g. in tests), use
	/// [`is_registered`](Self::is_registered).
	///
	/// [#3457]: https://github.com/kent8192/reinhardt-web/issues/3457
	pub fn register<T: Any + Send + Sync + 'static>(
		&self,
		scope: DependencyScope,
		factory: impl FactoryTrait + 'static,
	) {
		let type_id = TypeId::of::<T>();
		let type_name = std::any::type_name::<T>();
		// Check for duplicates before inserting so that no state is mutated on the
		// error path. This avoids leaving the registry inconsistent if the panic is
		// caught (e.g. factories pointing to the new registration while scopes still
		// reflects the old one).
		if self.factories.contains_key(&type_id) {
			let short = type_name.rsplit("::").next().unwrap_or(type_name);
			panic!(
				"Duplicate DependencyRegistry registration for type `{type_name}`.\n\
\n\
Hint: reinhardt DI uses TypeId as the sole registry key. Two factories\n\
returning the same type will conflict regardless of function name or scope.\n\
Use a distinct newtype (e.g., `struct Primary{short}({short})`) for each."
			);
		}
		self.factories.insert(type_id, Box::new(factory));
		self.scopes.insert(type_id, scope);
	}

	/// Register a simple async factory function
	pub fn register_async<T, F, Fut>(&self, scope: DependencyScope, factory: F)
	where
		T: Any + Send + Sync + 'static,
		F: Fn(Arc<InjectionContext>) -> Fut + Send + Sync + 'static,
		Fut: Future<Output = DiResult<T>> + Send + 'static,
	{
		self.register::<T>(scope, AsyncFactory::new(factory));
	}

	/// Get the scope for a type
	pub fn get_scope<T: Any + 'static>(&self) -> Option<DependencyScope> {
		let type_id = TypeId::of::<T>();
		self.scopes.get(&type_id).map(|entry| *entry.value())
	}

	/// Check if a type is registered
	pub fn is_registered<T: Any + 'static>(&self) -> bool {
		let type_id = TypeId::of::<T>();
		self.factories.contains_key(&type_id)
	}

	/// Get the number of registered dependencies
	pub fn len(&self) -> usize {
		self.factories.len()
	}

	/// Check if the registry is empty
	pub fn is_empty(&self) -> bool {
		self.factories.is_empty()
	}

	/// Create an instance using the registered factory
	pub async fn create<T: Any + Send + Sync + 'static>(
		&self,
		ctx: &InjectionContext,
	) -> DiResult<Arc<T>> {
		let type_id = TypeId::of::<T>();

		let factory = self.factories.get(&type_id).ok_or_else(|| {
			crate::DiError::DependencyNotRegistered {
				type_name: std::any::type_name::<T>().to_string(),
			}
		})?;

		let any_arc = factory.create(ctx).await?;

		any_arc
			.downcast::<T>()
			.map_err(|_| crate::DiError::Internal {
				message: format!(
					"Failed to downcast dependency: expected {}, got different type",
					std::any::type_name::<T>()
				),
			})
	}

	/// Get the direct dependencies of a type
	///
	/// Returns a vector of TypeIds representing the types that the given type directly depends on.
	pub fn get_dependencies(&self, type_id: TypeId) -> Vec<TypeId> {
		self.dependencies
			.get(&type_id)
			.map(|deps| deps.value().clone())
			.unwrap_or_default()
	}

	/// Get all dependencies in the registry
	///
	/// Returns a HashMap mapping each type to its direct dependencies.
	pub fn get_all_dependencies(&self) -> std::collections::HashMap<TypeId, Vec<TypeId>> {
		self.dependencies
			.iter()
			.map(|entry| (*entry.key(), entry.value().clone()))
			.collect()
	}

	/// Get all type names in the registry
	///
	/// Returns a HashMap mapping TypeIds to their human-readable type names.
	pub fn get_type_names(&self) -> std::collections::HashMap<TypeId, &'static str> {
		self.type_names
			.iter()
			.map(|entry| (*entry.key(), *entry.value()))
			.collect()
	}

	/// Register dependencies for a type
	///
	/// This is typically called automatically by the registration system.
	/// Not intended for direct use; exposed for macro-generated code.
	#[doc(hidden)]
	pub fn register_dependencies(&self, type_id: TypeId, deps: impl AsRef<[TypeId]>) {
		self.dependencies.insert(type_id, deps.as_ref().to_vec());
	}

	/// Register a type name for debugging
	///
	/// This is typically called automatically by the registration system.
	/// Not intended for direct use; exposed for macro-generated code.
	#[doc(hidden)]
	pub fn register_type_name(&self, type_id: TypeId, type_name: &'static str) {
		self.type_names.insert(type_id, type_name);
	}

	/// Check if a type is registered by its `TypeId`.
	pub(crate) fn is_registered_by_id(&self, type_id: TypeId) -> bool {
		self.factories.contains_key(&type_id)
	}

	/// Get the scope for a type by its `TypeId`.
	pub(crate) fn get_scope_by_id(&self, type_id: TypeId) -> Option<DependencyScope> {
		self.scopes.get(&type_id).map(|entry| *entry.value())
	}

	/// Get the type name for a `TypeId`.
	pub(crate) fn get_type_name(&self, type_id: TypeId) -> Option<&'static str> {
		self.type_names.get(&type_id).map(|entry| *entry.value())
	}

	/// Register the fully-qualified type name obtained from `std::any::type_name::<T>()`.
	///
	/// Used by the pseudo orphan rule to detect framework-managed types.
	#[doc(hidden)]
	pub fn register_qualified_type_name(&self, type_id: TypeId, qualified_name: &'static str) {
		self.qualified_type_names.insert(type_id, qualified_name);
	}

	/// Get the fully-qualified type name for a given `TypeId`.
	pub fn get_qualified_type_name(&self, type_id: &TypeId) -> Option<&'static str> {
		self.qualified_type_names.get(type_id).map(|r| *r.value())
	}

	/// Iterate over all qualified type name mappings without allocating a new map.
	pub fn iter_qualified_type_names(&self) -> impl Iterator<Item = (TypeId, &'static str)> + '_ {
		self.qualified_type_names
			.iter()
			.map(|entry| (*entry.key(), *entry.value()))
	}
}

#[cfg(feature = "testing")]
impl DependencyRegistry {
	/// Registers or overrides a factory for type `T` without panicking on
	/// duplicate registration.
	///
	/// Returns an [`OverrideGuard`](crate::testing::OverrideGuard) that
	/// restores the previous factory (or removes the entry entirely if there
	/// was none) when dropped.
	///
	/// When called on a **per-context** registry (created via
	/// `InjectionContextBuilder::with_registry`), each test operates on its
	/// own isolated registry and `#[serial(di_registry)]` is not required.
	///
	/// When called on the **global** registry (`global_registry()`), tests
	/// **must** run inside the `#[serial(di_registry)]` group because the
	/// shared registry is mutated non-atomically.
	///
	/// # Safety contract
	///
	/// This method inserts into two separate `DashMap`s (`factories` and
	/// `scopes`) non-atomically. When operating on a shared (global)
	/// registry, another thread can observe a torn state where the new
	/// factory is paired with the old scope (or vice versa). The
	/// `#[serial(di_registry)]` requirement eliminates that window for the
	/// global registry; per-context registries are isolated by design.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use std::sync::Arc;
	/// # use reinhardt_di::{DependencyRegistry, DependencyScope, DiResult, InjectionContext};
	/// # fn _example(registry: Arc<DependencyRegistry>) {
	/// let _guard = registry.register_override::<String, _, _>(
	///     DependencyScope::Singleton,
	///     |_ctx| async { Ok("mock".to_string()) },
	/// );
	/// // ... run test body ...
	/// // `_guard` dropped here → previous factory restored.
	/// # }
	/// ```
	pub fn register_override<T, F, Fut>(
		self: &std::sync::Arc<Self>,
		scope: crate::registry::DependencyScope,
		factory: F,
	) -> crate::testing::OverrideGuard
	where
		T: std::any::Any + Send + Sync + 'static,
		F: Fn(std::sync::Arc<crate::InjectionContext>) -> Fut + Send + Sync + 'static,
		Fut: std::future::Future<Output = crate::DiResult<T>> + Send + 'static,
	{
		let type_id = std::any::TypeId::of::<T>();
		let async_factory = crate::registry::AsyncFactory::new(factory);
		let boxed: Box<dyn crate::registry::FactoryTrait> = Box::new(async_factory);

		// Capture previous (if any) and install the override.
		let previous_factory = self.factories.insert(type_id, boxed);
		let previous_scope = self.scopes.insert(type_id, scope);

		// `factories` and `scopes` are always inserted/removed in lockstep, so
		// observing one without the other indicates the `#[serial(di_registry)]`
		// contract was violated by another writer. Assert in debug builds and
		// fall back to "no previous" in release so the guard at least removes
		// the entry instead of restoring a partial state.
		debug_assert!(
			previous_factory.is_some() == previous_scope.is_some(),
			"torn override state: factories/scopes diverged for `{}`",
			std::any::type_name::<T>()
		);
		let previous = match (previous_factory, previous_scope) {
			(Some(f), Some(s)) => Some((f, s)),
			_ => None,
		};

		crate::testing::OverrideGuard {
			type_id,
			previous,
			registry: std::sync::Arc::downgrade(self),
		}
	}

	/// Restores a previously-installed factory and scope. Used by
	/// [`OverrideGuard::drop`](crate::testing::OverrideGuard).
	///
	/// Like `register_override`, this performs a non-atomic two-`DashMap`
	/// mutation. For the global registry, callers MUST hold the
	/// `#[serial(di_registry)]` lock; for per-context registries, isolation
	/// is guaranteed by design.
	pub(crate) fn restore_override(
		&self,
		type_id: std::any::TypeId,
		factory: Box<dyn crate::registry::FactoryTrait>,
		scope: crate::registry::DependencyScope,
	) {
		self.factories.insert(type_id, factory);
		self.scopes.insert(type_id, scope);
	}

	/// Removes an override entry that had no prior registration. Used by
	/// [`OverrideGuard::drop`](crate::testing::OverrideGuard). Same
	/// serialization requirements as `restore_override`.
	pub(crate) fn remove_override(&self, type_id: std::any::TypeId) {
		self.factories.remove(&type_id);
		self.scopes.remove(&type_id);
	}
}

impl Default for DependencyRegistry {
	fn default() -> Self {
		Self::new()
	}
}

/// Global singleton registry instance
static GLOBAL_REGISTRY: OnceLock<Arc<DependencyRegistry>> = OnceLock::new();

/// Get the global registry instance
pub fn global_registry() -> &'static Arc<DependencyRegistry> {
	GLOBAL_REGISTRY.get_or_init(|| {
		let registry = Arc::new(DependencyRegistry::new());
		initialize_registry(&registry);
		registry
	})
}

/// Resets the global dependency registry for test isolation.
///
/// This replaces the `GLOBAL_REGISTRY` `OnceLock` with a fresh instance so
/// that the next call to `global_registry()` will re-initialize it.
///
/// # Safety
///
/// This function replaces a static `OnceLock` value using `std::ptr::write`.
/// It is only safe to call from a single-threaded test context (e.g., with
/// `#[serial]`) where no other thread is concurrently reading the registry.
#[cfg(test)]
pub fn reset_global_registry() {
	// SAFETY: We replace the OnceLock in-place with a fresh instance.
	// This is safe only when called from a single-threaded test context
	// (enforced by #[serial]) where no concurrent readers exist.
	unsafe {
		let ptr = std::ptr::addr_of!(GLOBAL_REGISTRY) as *mut OnceLock<Arc<DependencyRegistry>>;
		std::ptr::write(ptr, OnceLock::new());
	}
}

/// Registration entry for inventory collection
pub struct DependencyRegistration {
	/// The `TypeId` of the dependency being registered.
	pub type_id: TypeId,
	/// The human-readable name of the type.
	pub type_name: &'static str,
	/// The scope (request or singleton) for this dependency.
	pub scope: DependencyScope,
	/// Direct dependencies of this type.
	pub dependencies: &'static [TypeId],
	/// A function that registers this dependency's factory with the registry.
	pub register_fn: fn(&DependencyRegistry),
}

impl DependencyRegistration {
	/// Create a new registration entry
	pub const fn new<T: Send + Sync + 'static>(
		type_name: &'static str,
		scope: DependencyScope,
		register_fn: fn(&DependencyRegistry),
	) -> Self {
		Self {
			type_id: TypeId::of::<T>(),
			type_name,
			scope,
			dependencies: &[],
			register_fn,
		}
	}

	/// Create a new registration entry with explicit dependencies
	pub const fn new_with_deps<T: Send + Sync + 'static>(
		type_name: &'static str,
		scope: DependencyScope,
		dependencies: &'static [TypeId],
		register_fn: fn(&DependencyRegistry),
	) -> Self {
		Self {
			type_id: TypeId::of::<T>(),
			type_name,
			scope,
			dependencies,
			register_fn,
		}
	}
}

// Collect all dependency registrations at compile time
inventory::collect!(DependencyRegistration);

/// Const-constructible registration entry for `#[injectable]` structs with `#[scope]`.
///
/// Unlike `DependencyRegistration` which uses `Box<dyn Fn>` (non-const),
/// this struct stores a plain function pointer so it can be used in
/// `inventory::submit!` which requires const-evaluable expressions.
pub struct InjectableRegistration {
	/// A function that registers this type's factory with the registry.
	pub register_fn: fn(&DependencyRegistry),
}

impl InjectableRegistration {
	/// Create a new `InjectableRegistration` with a function pointer.
	pub const fn new(register_fn: fn(&DependencyRegistry)) -> Self {
		Self { register_fn }
	}
}

inventory::collect!(InjectableRegistration);

/// Initialize the registry with all collected registrations
fn initialize_registry(registry: &DependencyRegistry) {
	for registration in inventory::iter::<DependencyRegistration> {
		(registration.register_fn)(registry);
	}
	for registration in inventory::iter::<InjectableRegistration> {
		(registration.register_fn)(registry);
	}
}

/// Helper macro for submitting registrations to inventory
///
/// This is used internally by the `#[injectable]` and `#[injectable_factory]` macros.
#[macro_export]
macro_rules! submit_registration {
	($registration:expr) => {
		$crate::inventory::submit! {
			$registration
		}
	};
}

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

	#[derive(Clone)]
	struct TestService {
		value: i32,
	}

	#[rstest]
	#[tokio::test]
	async fn test_registry_basic() {
		let registry = DependencyRegistry::new();

		registry.register_async::<TestService, _, _>(DependencyScope::Singleton, |_ctx| async {
			Ok(TestService { value: 42 })
		});

		assert!(registry.is_registered::<TestService>());
		assert_eq!(
			registry.get_scope::<TestService>(),
			Some(DependencyScope::Singleton)
		);

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

		let service = registry.create::<TestService>(&ctx).await.unwrap();
		assert_eq!(service.value, 42);
	}

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

		let result = registry.create::<TestService>(&ctx).await;
		assert!(result.is_err());
	}

	// Fixes #3457
	#[rstest]
	fn test_duplicate_registration_panics() {
		let registry = DependencyRegistry::new();

		registry.register_async::<TestService, _, _>(DependencyScope::Singleton, |_ctx| async {
			Ok(TestService { value: 1 })
		});

		// Act
		let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
			registry.register_async::<TestService, _, _>(DependencyScope::Request, |_ctx| async {
				Ok(TestService { value: 2 })
			});
		}));

		// Assert
		let err = result.expect_err("expected panic on duplicate registration");
		let msg = err
			.downcast_ref::<String>()
			.map(|s| s.as_str())
			.or_else(|| err.downcast_ref::<&str>().copied())
			.expect("panic payload should be a string");
		assert!(
			msg.contains("Duplicate DependencyRegistry registration"),
			"missing duplicate prefix: {msg}"
		);
		assert!(
			msg.contains("TestService"),
			"missing type name in panic message: {msg}"
		);
		assert!(
			msg.contains("newtype"),
			"missing newtype hint in panic message: {msg}"
		);
	}

	// Fixes #3457 — is_registered guard prevents panic (test helper pattern)
	#[rstest]
	fn test_is_registered_guard_allows_skip() {
		let registry = DependencyRegistry::new();

		registry.register_async::<TestService, _, _>(DependencyScope::Singleton, |_ctx| async {
			Ok(TestService { value: 1 })
		});

		// Second registration guarded — no panic
		if !registry.is_registered::<TestService>() {
			registry.register_async::<TestService, _, _>(DependencyScope::Request, |_ctx| async {
				Ok(TestService { value: 2 })
			});
		}

		assert!(registry.is_registered::<TestService>());
	}
}