dependency-injector 1.0.0

High-performance, lock-free dependency injection container for Rust
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
//! Compile-Time Type-Safe Container Builder
//!
//! This module provides a type-state container builder that ensures
//! type safety at compile time using Rust's type system.
//!
//! # Features
//!
//! - **Zero runtime overhead**: Type checking happens at compile time
//! - **Builder pattern**: Fluent API that tracks registered types
//! - **Dependency verification**: Ensure deps are registered before dependents
//!
//! # Example
//!
//! ```rust
//! use dependency_injector::typed::TypedBuilder;
//!
//! #[derive(Clone)]
//! struct Database { url: String }
//!
//! #[derive(Clone)]
//! struct Cache { size: usize }
//!
//! // Build with compile-time type tracking
//! let container = TypedBuilder::new()
//!     .singleton(Database { url: "postgres://localhost".into() })
//!     .singleton(Cache { size: 1024 })
//!     .build();
//!
//! // Type-safe resolution
//! let db = container.get::<Database>();
//! let cache = container.get::<Cache>();
//! ```
//!
//! # Compile-Time Dependency Declaration
//!
//! ```rust
//! use dependency_injector::typed::{TypedBuilder, DeclaresDeps};
//!
//! #[derive(Clone)]
//! struct Database;
//!
//! #[derive(Clone)]
//! struct UserService;
//!
//! // Declare that UserService depends on Database
//! impl DeclaresDeps for UserService {
//!     fn dependency_names() -> &'static [&'static str] {
//!         &["Database"]
//!     }
//! }
//!
//! // Register deps first, then dependent
//! let container = TypedBuilder::new()
//!     .singleton(Database)
//!     .with_deps(UserService)
//!     .build();
//! ```

use crate::{Container, Injectable};
use std::marker::PhantomData;
use std::sync::Arc;

// =============================================================================
// Registry Marker Types
// =============================================================================

/// Marker for a registered type in the builder's registry.
pub struct Reg<T, Rest>(PhantomData<(T, Rest)>);

/// Trait for checking if type T is at the head of a registry.
pub trait HasType<T: Injectable> {}

impl<T: Injectable, Rest> HasType<T> for Reg<T, Rest> {}

// =============================================================================
// Type-State Builder
// =============================================================================

/// A type-state container builder.
///
/// The type parameter `R` tracks all registered types at compile time.
pub struct TypedBuilder<R = ()> {
    container: Container,
    _registry: PhantomData<R>,
}

impl TypedBuilder<()> {
    /// Create a new typed builder.
    #[inline]
    pub fn new() -> Self {
        Self {
            container: Container::new(),
            _registry: PhantomData,
        }
    }

    /// Create with pre-allocated capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            container: Container::with_capacity(capacity),
            _registry: PhantomData,
        }
    }
}

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

impl<R> TypedBuilder<R> {
    /// Register a singleton service.
    #[inline]
    pub fn singleton<T: Injectable>(self, instance: T) -> TypedBuilder<Reg<T, R>> {
        self.container.singleton(instance);
        TypedBuilder {
            container: self.container,
            _registry: PhantomData,
        }
    }

    /// Register a lazy singleton.
    #[inline]
    pub fn lazy<T: Injectable, F>(self, factory: F) -> TypedBuilder<Reg<T, R>>
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.container.lazy(factory);
        TypedBuilder {
            container: self.container,
            _registry: PhantomData,
        }
    }

    /// Register a transient service.
    #[inline]
    pub fn transient<T: Injectable, F>(self, factory: F) -> TypedBuilder<Reg<T, R>>
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.container.transient(factory);
        TypedBuilder {
            container: self.container,
            _registry: PhantomData,
        }
    }

    /// Build the typed container.
    #[inline]
    pub fn build(self) -> TypedContainer<R> {
        self.container.lock();
        TypedContainer {
            container: self.container,
            _registry: PhantomData,
        }
    }

    /// Build and return the underlying container.
    #[inline]
    pub fn build_dynamic(self) -> Container {
        self.container.lock();
        self.container
    }

    /// Access the underlying container.
    #[inline]
    pub fn inner(&self) -> &Container {
        &self.container
    }
}

// =============================================================================
// Dependency Declaration
// =============================================================================

// =============================================================================
// Dependency Declaration (Runtime-Verified)
// =============================================================================

/// Trait for services that declare their dependencies.
///
/// Use with `with_deps` to get documentation-level dependency declaration.
/// Runtime verification ensures all dependencies are present.
///
/// Note: Full compile-time dependency verification requires proc macros
/// or unstable Rust features. This provides a documentation/runtime hybrid.
pub trait DeclaresDeps: Injectable {
    /// List of dependency type names (for documentation and debugging).
    fn dependency_names() -> &'static [&'static str] {
        &[]
    }
}

impl<R> TypedBuilder<R> {
    /// Register a service (alias for singleton with deps intent).
    ///
    /// Note: This method is the same as `singleton` but signals that
    /// the service has dependencies that should already be registered.
    #[inline]
    pub fn with_deps<T: DeclaresDeps>(self, instance: T) -> TypedBuilder<Reg<T, R>> {
        self.singleton(instance)
    }

    /// Register a lazy service with deps intent.
    #[inline]
    pub fn lazy_with_deps<T: DeclaresDeps, F>(self, factory: F) -> TypedBuilder<Reg<T, R>>
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        self.lazy(factory)
    }
}

// Dummy traits for backwards compatibility
pub trait VerifyDeps<D> {}
impl<R, D> VerifyDeps<D> for R {}

// =============================================================================
// Typed Container
// =============================================================================

/// A container with compile-time type tracking.
///
/// The type parameter tracks what was registered, enabling
/// compile-time verification of service access.
pub struct TypedContainer<R> {
    container: Container,
    _registry: PhantomData<R>,
}

impl<R> TypedContainer<R> {
    /// Resolve a service by type.
    ///
    /// Uses the dynamic container internally but provides type-safe API.
    #[inline]
    pub fn get<T: Injectable>(&self) -> Arc<T> {
        self.container
            .get::<T>()
            .expect("TypedContainer: service not found (registration mismatch)")
    }

    /// Try to resolve a service.
    #[inline]
    pub fn try_get<T: Injectable>(&self) -> Option<Arc<T>> {
        self.container.try_get::<T>()
    }

    /// Check if service exists.
    #[inline]
    pub fn contains<T: Injectable>(&self) -> bool {
        self.container.contains::<T>()
    }

    /// Create a dynamic child scope.
    #[inline]
    pub fn scope(&self) -> Container {
        self.container.scope()
    }

    /// Access the underlying container.
    #[inline]
    pub fn inner(&self) -> &Container {
        &self.container
    }

    /// Convert to the underlying container.
    #[inline]
    pub fn into_inner(self) -> Container {
        self.container
    }
}

impl<R> Clone for TypedContainer<R> {
    fn clone(&self) -> Self {
        Self {
            container: self.container.clone(),
            _registry: PhantomData,
        }
    }
}

impl<R> std::fmt::Debug for TypedContainer<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TypedContainer")
            .field("inner", &self.container)
            .finish()
    }
}

// =============================================================================
// Backward Compatibility Aliases
// =============================================================================

/// Alias for HasType trait.
pub trait Has<T: Injectable>: HasType<T> {}
impl<T: Injectable, R: HasType<T>> Has<T> for R {}

/// Alias for HasType trait.
pub trait HasService<T: Injectable>: HasType<T> {}
impl<T: Injectable, R: HasType<T>> HasService<T> for R {}

// Dummy trait for DepsPresent compatibility
pub trait DepsPresent<D> {}
impl<R, D> DepsPresent<D> for R {}

// =============================================================================
// Tests
// =============================================================================

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

    #[derive(Clone)]
    struct Database {
        url: String,
    }

    #[derive(Clone)]
    struct Cache {
        size: usize,
    }

    #[derive(Clone)]
    struct UserService;

    impl DeclaresDeps for UserService {
        fn dependency_names() -> &'static [&'static str] {
            &["Database", "Cache"]
        }
    }

    #[test]
    fn test_typed_builder_basic() {
        let container = TypedBuilder::new()
            .singleton(Database {
                url: "postgres://localhost".into(),
            })
            .singleton(Cache { size: 1024 })
            .build();

        let db = container.get::<Database>();
        let cache = container.get::<Cache>();

        assert_eq!(db.url, "postgres://localhost");
        assert_eq!(cache.size, 1024);
    }

    #[test]
    fn test_typed_builder_lazy() {
        let container = TypedBuilder::new()
            .lazy(|| Database {
                url: "lazy://created".into(),
            })
            .build();

        let db = container.get::<Database>();
        assert_eq!(db.url, "lazy://created");
    }

    #[test]
    fn test_typed_builder_transient() {
        use std::sync::atomic::{AtomicU32, Ordering};

        static COUNTER: AtomicU32 = AtomicU32::new(0);

        #[derive(Clone)]
        struct Counter(u32);

        let container = TypedBuilder::new()
            .transient(|| Counter(COUNTER.fetch_add(1, Ordering::SeqCst)))
            .build();

        let c1 = container.get::<Counter>();
        let c2 = container.get::<Counter>();

        assert_ne!(c1.0, c2.0);
    }

    #[test]
    fn test_typed_container_clone() {
        let container = TypedBuilder::new()
            .singleton(Database { url: "test".into() })
            .build();

        let container2 = container.clone();

        let db1 = container.get::<Database>();
        let db2 = container2.get::<Database>();

        assert!(Arc::ptr_eq(&db1, &db2));
    }

    #[test]
    fn test_with_dependencies() {
        // Register deps first, then dependent service
        let container = TypedBuilder::new()
            .singleton(Database { url: "pg".into() })
            .singleton(Cache { size: 100 })
            .with_deps(UserService)
            .build();

        let _ = container.get::<UserService>();
    }

    #[test]
    fn test_many_services() {
        #[derive(Clone)]
        struct S1;
        #[derive(Clone)]
        struct S2;
        #[derive(Clone)]
        struct S3;
        #[derive(Clone)]
        struct S4;
        #[derive(Clone)]
        struct S5;

        let container = TypedBuilder::new()
            .singleton(S1)
            .singleton(S2)
            .singleton(S3)
            .singleton(S4)
            .singleton(S5)
            .build();

        let _ = container.get::<S1>();
        let _ = container.get::<S2>();
        let _ = container.get::<S3>();
        let _ = container.get::<S4>();
        let _ = container.get::<S5>();
    }

    #[test]
    fn test_scope_from_typed() {
        let container = TypedBuilder::new()
            .singleton(Database { url: "root".into() })
            .build();

        let child = container.scope();
        child.singleton(Cache { size: 256 });

        assert!(child.contains::<Database>());
        assert!(child.contains::<Cache>());
    }
}