injectable-rs 0.1.0

A compile-time dependency injection framework for Rust using extractor-based DI
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
//! Integration tests for the `bind!` macro and `#[injectable(trait)]`.
//!
//! # What is tested
//!
//! - Basic resolution: `bind!(dyn Trait => Concrete)` registers an
//!   `InjectableArcFactory` keyed by `Arc<dyn Trait>`, making the trait
//!   object resolvable via `container.resolve_external::<Arc<dyn Trait>>()`.
//! - Field injection: `Inject<dyn Trait>` as a struct field in `#[injectable]`.
//! - Constructor injection: `Inject<dyn Trait>` as a `#[injectable(ctor)]` param.
//! - Trait method dispatch through the erased pointer.
//! - `Deref` ergonomics on `Inject<dyn Trait>`.
//! - Scope semantics: `bind!` calls `Provider::provide` directly (not through
//!   the singleton cache), so each resolution of `Inject<dyn Trait>` produces
//!   a FRESH concrete instance, even if the concrete type is declared singleton.
//! - Dependency resolution: the concrete type's own deps (e.g. `Inject<Config>`)
//!   are resolved through the normal scope-respecting path.
//! - `Option<Inject<dyn Trait>>`: resolves to `Some` when a binding exists.
//! - Lifecycle hooks: `#[injectable(post_construct)]` and `#[injectable(pre_destruct)]` run correctly.
//! - Multiple distinct trait bindings in the same container.
//! - Async trait methods dispatched through the trait object.
//! - `inject_fn` receiving `Inject<dyn Trait>` parameters.
//! - `bind!` without `#[injectable(trait)]` (any trait qualifies).
//!
//! # One binding per trait per binary
//!
//! Each `bind!(dyn Trait => Concrete)` generates a global `InjectableArcFactory`
//! entry.  Only ONE binding per trait is meaningful per compilation unit —
//! multiple `bind!` calls for the same trait are allowed at link time (both
//! entries exist in inventory) but only the first one found will be used.
//! Each test section uses a distinct trait name to avoid ambiguity.

use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

use injectable_rs::prelude::*;

// ── Helper: resolve Arc<dyn T> and wrap in Inject ────────────────────────
// `container.resolve::<Inject<dyn T>>()` requires `Inject<dyn T>: Injectable`
// (which it isn't).  Use `resolve_external::<Arc<dyn T>>()` instead.
macro_rules! resolve_dyn {
    ($container:expr, $dyn_ty:ty) => {{
        let arc: Arc<$dyn_ty> = $container.resolve_external::<Arc<$dyn_ty>>().await.unwrap();
        Inject::new(arc)
    }};
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 1 — Basic resolution and method dispatch
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
trait Greeter: Send + Sync {
    fn greet(&self, name: &str) -> String;
}

#[injectable]
#[derive(Default, Clone)]
struct EnglishGreeter;

impl Greeter for EnglishGreeter {
    fn greet(&self, name: &str) -> String {
        format!("Hello, {name}!")
    }
}

bind!(dyn Greeter => EnglishGreeter);

#[tokio::test]
async fn bind_resolves_arc_dyn_trait_via_resolve_external() {
    let container = Container::builder().build().await.unwrap();
    let arc: Arc<dyn Greeter> = container
        .resolve_external::<Arc<dyn Greeter>>()
        .await
        .unwrap();
    assert_eq!(arc.greet("world"), "Hello, world!");
}

#[tokio::test]
async fn inject_new_wraps_arc_dyn_trait() {
    let container = Container::builder().build().await.unwrap();
    let g: Inject<dyn Greeter> = resolve_dyn!(container, dyn Greeter);
    assert_eq!(g.greet("Alice"), "Hello, Alice!");
}

#[tokio::test]
async fn deref_through_inject_dyn_trait() {
    let container = Container::builder().build().await.unwrap();
    let g: Inject<dyn Greeter> = resolve_dyn!(container, dyn Greeter);
    // Inject<T> implements Deref — no explicit (*g) needed
    let result = g.greet("Bob");
    assert_eq!(result, "Hello, Bob!");
}

#[tokio::test]
async fn into_inner_gives_arc_dyn_trait() {
    let container = Container::builder().build().await.unwrap();
    let g: Inject<dyn Greeter> = resolve_dyn!(container, dyn Greeter);
    let arc: Arc<dyn Greeter> = g.into_inner();
    assert_eq!(arc.greet("Carol"), "Hello, Carol!");
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 2 — Field injection: Inject<dyn Trait> inside an #[injectable] struct
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
trait Logger: Send + Sync {
    fn log(&self, msg: &str) -> String;
}

#[injectable]
#[derive(Default, Clone)]
struct StdoutLogger;

impl Logger for StdoutLogger {
    fn log(&self, msg: &str) -> String {
        format!("[INFO] {msg}")
    }
}

bind!(dyn Logger => StdoutLogger);

#[injectable]
struct RequestHandler {
    logger: Inject<dyn Logger>,
}

impl RequestHandler {
    fn handle(&self, req: &str) -> String {
        self.logger.log(&format!("handling {req}"))
    }
}

#[tokio::test]
async fn field_injection_inject_dyn_trait() {
    let container = Container::builder().build().await.unwrap();
    let handler: RequestHandler = container.resolve().await.unwrap();
    assert_eq!(handler.handle("GET /"), "[INFO] handling GET /");
}

#[tokio::test]
async fn field_inject_dyn_trait_method_dispatch() {
    let container = Container::builder().build().await.unwrap();
    let handler: RequestHandler = container.resolve().await.unwrap();
    assert!(handler.handle("POST /api").contains("[INFO]"));
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 3 — Constructor injection: Inject<dyn Trait> as a #[injectable(ctor)] param
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
trait Serializer: Send + Sync {
    fn serialize(&self, value: u32) -> String;
}

#[injectable]
#[derive(Default, Clone)]
struct JsonSerializer;

impl Serializer for JsonSerializer {
    fn serialize(&self, value: u32) -> String {
        format!(r#"{{"value":{value}}}"#)
    }
}

bind!(dyn Serializer => JsonSerializer);

struct ApiController {
    serializer: Inject<dyn Serializer>,
}

#[injectable]
impl ApiController {
    #[injectable(ctor)]
    fn new(serializer: Inject<dyn Serializer>) -> Self {
        Self { serializer }
    }
    fn respond(&self, n: u32) -> String {
        self.serializer.serialize(n)
    }
}

#[tokio::test]
async fn ctor_injection_inject_dyn_trait() {
    let container = Container::builder().build().await.unwrap();
    let ctrl: ApiController = container.resolve().await.unwrap();
    assert_eq!(ctrl.respond(42), r#"{"value":42}"#);
}

#[tokio::test]
async fn ctor_inject_dyn_multiple_calls() {
    let container = Container::builder().build().await.unwrap();
    let ctrl: ApiController = container.resolve().await.unwrap();
    assert_eq!(ctrl.respond(0), r#"{"value":0}"#);
    assert_eq!(ctrl.respond(999), r#"{"value":999}"#);
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 4 — Scope semantics: bind! bypasses the singleton cache
//
// `bind!`'s `provide_fn` calls `Provider::provide` directly — it does NOT go
// through `resolve_singleton_arc`.  As a result, each resolution of
// `Inject<dyn Trait>` (or `Arc<dyn Trait>`) produces a FRESH concrete instance,
// regardless of whether the concrete type itself is declared singleton.
// ═══════════════════════════════════════════════════════════════════════════

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

#[injectable(trait)]
trait Counter: Send + Sync {
    fn id(&self) -> u32;
}

#[derive(Clone)]
struct CounterImpl {
    id: u32,
}

#[injectable]
impl CounterImpl {
    #[injectable(ctor)]
    fn new() -> Self {
        let n = COUNTER_CTOR_CALLS.fetch_add(1, Ordering::SeqCst);
        Self { id: n }
    }
}

impl Counter for CounterImpl {
    fn id(&self) -> u32 {
        self.id
    }
}

bind!(dyn Counter => CounterImpl);

#[tokio::test]
async fn bind_bypasses_singleton_cache_each_resolution_is_fresh() {
    COUNTER_CTOR_CALLS.store(0, Ordering::SeqCst);

    let container = Container::builder().build().await.unwrap();
    let a: Inject<dyn Counter> = resolve_dyn!(container, dyn Counter);
    let b: Inject<dyn Counter> = resolve_dyn!(container, dyn Counter);

    // Fresh instances → different IDs.
    assert_ne!(
        a.id(),
        b.id(),
        "bind! bypasses the singleton cache: each Arc<dyn Counter> \
         resolution should produce a distinct CounterImpl"
    );
    assert!(COUNTER_CTOR_CALLS.load(Ordering::SeqCst) >= 2);
}

#[injectable]
struct ServiceA {
    counter: Inject<dyn Counter>,
}

#[injectable]
struct ServiceB {
    counter: Inject<dyn Counter>,
}

#[tokio::test]
async fn two_services_each_get_distinct_arc_from_bind() {
    let container = Container::builder().build().await.unwrap();
    let a: ServiceA = container.resolve().await.unwrap();
    let b: ServiceB = container.resolve().await.unwrap();
    assert_ne!(
        a.counter.id(),
        b.counter.id(),
        "ServiceA and ServiceB should each get their own CounterImpl"
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 5 — Concrete type's deps are resolved through normal scope machinery
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Clone, Debug)]
struct SharedConfig {
    value: u32,
}

#[injectable]
impl SharedConfig {
    #[injectable(ctor)]
    fn new() -> Self {
        Self { value: 0 }
    }
}

#[injectable(trait)]
trait Reporter: Send + Sync {
    fn report(&self) -> u32;
}

#[derive(Clone)]
struct ConfigReporter {
    cfg: Inject<SharedConfig>,
}

#[injectable]
impl ConfigReporter {
    #[injectable(ctor)]
    fn new(cfg: Inject<SharedConfig>) -> Self {
        Self { cfg }
    }
}

impl Reporter for ConfigReporter {
    fn report(&self) -> u32 {
        self.cfg.value
    }
}

bind!(dyn Reporter => ConfigReporter);

#[tokio::test]
async fn bound_concrete_deps_resolved_through_normal_path() {
    let container = Container::builder().build().await.unwrap();
    let r1: Inject<dyn Reporter> = resolve_dyn!(container, dyn Reporter);
    let r2: Inject<dyn Reporter> = resolve_dyn!(container, dyn Reporter);
    // Both reporters read from the same SharedConfig singleton.
    assert_eq!(r1.report(), r2.report());
    let cfg: SharedConfig = container.resolve().await.unwrap();
    assert_eq!(r1.report(), cfg.value);
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 6 — Option<Inject<dyn Trait>>
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
trait Formatter: Send + Sync {
    fn fmt_num(&self, n: u32) -> String;
}

#[injectable]
#[derive(Default, Clone)]
struct HexFormatter;

impl Formatter for HexFormatter {
    fn fmt_num(&self, n: u32) -> String {
        format!("{n:#010x}")
    }
}

bind!(dyn Formatter => HexFormatter);

#[injectable]
struct Printer {
    #[injectable(inject)]
    formatter: Option<Inject<dyn Formatter>>,
}

impl Printer {
    fn print(&self, n: u32) -> String {
        match &self.formatter {
            Some(f) => f.fmt_num(n),
            None => n.to_string(),
        }
    }
}

#[tokio::test]
async fn option_inject_dyn_trait_is_some_when_bound() {
    let container = Container::builder().build().await.unwrap();
    let printer: Printer = container.resolve().await.unwrap();
    assert!(
        printer.formatter.is_some(),
        "formatter should be Some — bind! is in scope"
    );
    assert_eq!(printer.print(255), "0x000000ff");
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 7 — post_construct runs for the bound concrete type
// ═══════════════════════════════════════════════════════════════════════════

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

#[injectable(trait)]
trait Warmer: Send + Sync {
    fn ping(&self) -> &'static str;
}

#[derive(Clone)]
struct HotCache;

#[injectable]
impl HotCache {
    #[injectable(ctor)]
    fn new() -> Self {
        Self
    }

    #[injectable(post_construct)]
    async fn warm_up(&self) -> HookResult {
        POST_CONSTRUCT_CALLED.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
}

impl Warmer for HotCache {
    fn ping(&self) -> &'static str {
        "warm"
    }
}

bind!(dyn Warmer => HotCache);

#[tokio::test]
async fn post_construct_runs_per_bind_resolution() {
    // Build once; verify that post_construct increments by exactly 1 per resolution
    // of Inject<dyn Warmer> (bind! bypasses the singleton cache, so the provider
    // runs fresh for every extraction).
    let container = Container::builder().build().await.unwrap();

    let n0 = POST_CONSTRUCT_CALLED.load(Ordering::SeqCst);
    let _: Inject<dyn Warmer> = resolve_dyn!(container, dyn Warmer);
    let n1 = POST_CONSTRUCT_CALLED.load(Ordering::SeqCst);
    assert_eq!(
        n1 - n0,
        1,
        "first resolution should trigger one post_construct"
    );

    let _: Inject<dyn Warmer> = resolve_dyn!(container, dyn Warmer);
    let n2 = POST_CONSTRUCT_CALLED.load(Ordering::SeqCst);
    assert_eq!(
        n2 - n1,
        1,
        "second resolution should trigger another post_construct"
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 8 — pre_destruct runs on shutdown for the bound type
// ═══════════════════════════════════════════════════════════════════════════

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

#[injectable(trait)]
trait Drainable: Send + Sync {
    fn name(&self) -> &'static str;
}

#[derive(Clone)]
struct DrainablePool;

#[injectable]
impl DrainablePool {
    #[injectable(ctor)]
    fn new() -> Self {
        Self
    }

    #[injectable(pre_destruct)]
    async fn drain(&self) -> HookResult {
        PRE_DESTRUCT_CALLED.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
}

impl Drainable for DrainablePool {
    fn name(&self) -> &'static str {
        "pool"
    }
}

bind!(dyn Drainable => DrainablePool);

#[tokio::test]
async fn pre_destruct_runs_on_shutdown_for_bound_type() {
    let before = PRE_DESTRUCT_CALLED.load(Ordering::SeqCst);
    let container = Container::builder().build().await.unwrap();
    let _: Inject<dyn Drainable> = resolve_dyn!(container, dyn Drainable);
    container.shutdown().await.expect("shutdown should succeed");
    let after = PRE_DESTRUCT_CALLED.load(Ordering::SeqCst);
    assert_eq!(
        after - before,
        1,
        "#[injectable(pre_destruct)] should be called once on shutdown"
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 9 — Multiple distinct trait bindings in the same container
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
trait Hasher: Send + Sync {
    fn hash_val(&self, input: &str) -> u64;
}

#[injectable(trait)]
trait Encoder: Send + Sync {
    fn encode_bytes(&self, bytes: &[u8]) -> String;
}

#[injectable]
#[derive(Default, Clone)]
struct FnvHasher;

impl Hasher for FnvHasher {
    fn hash_val(&self, input: &str) -> u64 {
        let mut h: u32 = 2_166_136_261;
        for b in input.bytes() {
            h ^= b as u32;
            h = h.wrapping_mul(16_777_619);
        }
        h as u64
    }
}

bind!(dyn Hasher => FnvHasher);

#[injectable]
#[derive(Default, Clone)]
struct HexEncoder;

impl Encoder for HexEncoder {
    fn encode_bytes(&self, bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{b:02x}")).collect()
    }
}

bind!(dyn Encoder => HexEncoder);

#[injectable]
struct Pipeline {
    hasher: Inject<dyn Hasher>,
    encoder: Inject<dyn Encoder>,
}

impl Pipeline {
    fn run(&self, input: &str) -> String {
        let hash_bytes = self.hasher.hash_val(input).to_le_bytes();
        self.encoder.encode_bytes(&hash_bytes)
    }
}

#[tokio::test]
async fn multiple_trait_bindings_in_same_container() {
    let container = Container::builder().build().await.unwrap();
    let pipeline: Pipeline = container.resolve().await.unwrap();
    let result = pipeline.run("hello");
    assert_eq!(result.len(), 16, "8-byte hash as 16 hex chars");
}

#[tokio::test]
async fn distinct_traits_resolve_independently() {
    let container = Container::builder().build().await.unwrap();
    let h: Inject<dyn Hasher> = resolve_dyn!(container, dyn Hasher);
    let e: Inject<dyn Encoder> = resolve_dyn!(container, dyn Encoder);
    let hash = h.hash_val("test");
    let encoded = e.encode_bytes(&hash.to_le_bytes());
    assert!(!encoded.is_empty());
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 10 — Async trait methods dispatched through the trait object
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
#[async_trait::async_trait]
trait AsyncFetcher: Send + Sync {
    async fn fetch(&self, id: u32) -> String;
}

#[injectable]
#[derive(Default, Clone)]
struct StubFetcher;

#[async_trait::async_trait]
impl AsyncFetcher for StubFetcher {
    async fn fetch(&self, id: u32) -> String {
        format!("item-{id}")
    }
}

bind!(dyn AsyncFetcher => StubFetcher);

#[injectable]
struct FetchService {
    fetcher: Inject<dyn AsyncFetcher>,
}

impl FetchService {
    async fn get(&self, id: u32) -> String {
        self.fetcher.fetch(id).await
    }
}

#[tokio::test]
async fn async_trait_method_dispatched_through_bind() {
    let container = Container::builder().build().await.unwrap();
    let svc: FetchService = container.resolve().await.unwrap();
    assert_eq!(svc.get(99).await, "item-99");
}

#[tokio::test]
async fn async_trait_method_multiple_calls() {
    let container = Container::builder().build().await.unwrap();
    let svc: FetchService = container.resolve().await.unwrap();
    for i in 0..5u32 {
        assert_eq!(svc.get(i).await, format!("item-{i}"));
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 11 — Deep service graph with a trait-bound leaf
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
trait TokenStore: Send + Sync {
    fn store(&self, token: &str) -> String;
}

#[injectable]
#[derive(Default, Clone)]
struct InMemoryTokenStore;

impl TokenStore for InMemoryTokenStore {
    fn store(&self, token: &str) -> String {
        format!("stored:{token}")
    }
}

bind!(dyn TokenStore => InMemoryTokenStore);

#[injectable]
#[derive(Default, Clone, Debug)]
struct UserDb;

#[injectable]
struct AuthService {
    store: Inject<dyn TokenStore>,
    db: Inject<UserDb>,
}

impl AuthService {
    fn login(&self, user: &str) -> String {
        let token = format!("{user}-tok");
        self.store.store(&token)
    }
}

#[injectable]
struct AppFacade {
    auth: Inject<AuthService>,
}

impl AppFacade {
    fn authenticate(&self, user: &str) -> String {
        self.auth.login(user)
    }
}

#[tokio::test]
async fn deep_service_graph_with_trait_bound_leaf() {
    let container = Container::builder().build().await.unwrap();
    let facade: AppFacade = container.resolve().await.unwrap();
    assert_eq!(facade.authenticate("alice"), "stored:alice-tok");
}

#[tokio::test]
async fn authservice_singleton_shared_across_facades() {
    // Both facades hold Inject<AuthService> from the singleton cache.
    // We verify indirectly: two facades authenticate identically.
    let container = Container::builder().build().await.unwrap();
    let f1: AppFacade = container.resolve().await.unwrap();
    let f2: AppFacade = container.resolve().await.unwrap();
    assert_eq!(f1.authenticate("alice"), f2.authenticate("alice"));
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 12 — Trait method reads from an injected singleton dependency
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Clone)]
struct AppVersion {
    version: &'static str,
}

#[injectable]
impl AppVersion {
    #[injectable(ctor)]
    fn new() -> Self {
        Self { version: "1.2.3" }
    }
}

#[injectable(trait)]
trait VersionProvider: Send + Sync {
    fn version(&self) -> &str;
}

#[derive(Clone)]
struct BuildInfoProvider {
    app_version: Inject<AppVersion>,
}

#[injectable]
impl BuildInfoProvider {
    #[injectable(ctor)]
    fn new(app_version: Inject<AppVersion>) -> Self {
        Self { app_version }
    }
}

impl VersionProvider for BuildInfoProvider {
    fn version(&self) -> &str {
        self.app_version.version
    }
}

bind!(dyn VersionProvider => BuildInfoProvider);

#[injectable]
struct HealthCheck {
    version: Inject<dyn VersionProvider>,
}

#[tokio::test]
async fn trait_method_reads_from_injected_singleton_dep() {
    let container = Container::builder().build().await.unwrap();
    let hc: HealthCheck = container.resolve().await.unwrap();
    assert_eq!(hc.version.version(), "1.2.3");
}

#[tokio::test]
async fn trait_binding_and_direct_resolve_read_same_dep() {
    let container = Container::builder().build().await.unwrap();
    let hc: HealthCheck = container.resolve().await.unwrap();
    let av: AppVersion = container.resolve().await.unwrap();
    assert_eq!(hc.version.version(), av.version);
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 13 — Arc from Inject<dyn Trait> can be cloned and shared
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
trait Validator: Send + Sync {
    fn validate(&self, input: &str) -> bool;
}

#[injectable]
#[derive(Default, Clone)]
struct NonEmptyValidator;

impl Validator for NonEmptyValidator {
    fn validate(&self, input: &str) -> bool {
        !input.is_empty()
    }
}

bind!(dyn Validator => NonEmptyValidator);

#[injectable]
struct ValidatorService {
    validator: Inject<dyn Validator>,
}

#[tokio::test]
async fn arc_dyn_trait_can_be_cloned_and_shared() {
    let container = Container::builder().build().await.unwrap();
    let svc: ValidatorService = container.resolve().await.unwrap();
    let arc1 = svc.validator.arc();
    let arc2 = Arc::clone(&arc1);

    assert!(arc1.validate("hello"));
    assert!(!arc2.validate(""));
    assert!(Arc::ptr_eq(&arc1, &arc2));
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 14 — inject_fn receiving Inject<dyn Trait>
// ═══════════════════════════════════════════════════════════════════════════

#[injectable(trait)]
trait Signer: Send + Sync {
    fn sign(&self, data: &str) -> String;
}

#[injectable]
#[derive(Default, Clone)]
struct HmacSigner;

impl Signer for HmacSigner {
    fn sign(&self, data: &str) -> String {
        format!("sig:{data}")
    }
}

bind!(dyn Signer => HmacSigner);

#[injectable(factory)]
async fn make_signed_payload(signer: Inject<dyn Signer>) -> String {
    signer.sign("payload")
}

struct SignedService {
    payload: String,
}

#[injectable]
impl SignedService {
    #[injectable(ctor)]
    async fn new(
        #[injectable(inject(use_factory_async = self::make_signed_payload))] payload: String,
    ) -> Self {
        Self { payload }
    }
}

#[tokio::test]
async fn inject_fn_receives_inject_dyn_trait() {
    let container = Container::builder().build().await.unwrap();
    let svc: SignedService = container.resolve().await.unwrap();
    assert_eq!(svc.payload, "sig:payload");
}

// ═══════════════════════════════════════════════════════════════════════════
// Section 15 — bind! works without #[injectable(trait)]
// ═══════════════════════════════════════════════════════════════════════════

// Deliberately NOT annotated with #[injectable(trait)].
trait RawTrait: Send + Sync {
    fn value(&self) -> i32;
}

#[injectable]
#[derive(Default, Clone)]
struct RawImpl;

impl RawTrait for RawImpl {
    fn value(&self) -> i32 {
        99
    }
}

bind!(dyn RawTrait => RawImpl);

#[injectable]
struct RawService {
    inner: Inject<dyn RawTrait>,
}

#[tokio::test]
async fn bind_works_without_injectable_trait_annotation() {
    let container = Container::builder().build().await.unwrap();
    let svc: RawService = container.resolve().await.unwrap();
    assert_eq!(svc.inner.value(), 99);
}

#[tokio::test]
async fn bind_raw_trait_direct_arc_resolution() {
    let container = Container::builder().build().await.unwrap();
    let arc: Arc<dyn RawTrait> = container
        .resolve_external::<Arc<dyn RawTrait>>()
        .await
        .unwrap();
    assert_eq!(arc.value(), 99);
}