more-di 3.1.0

Provides support for dependency injection (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
use crate::{
    KeyedRef, KeyedRefMut, Mut, ServiceDescriptor, Ref, RefMut, Type,
};
use std::any::{type_name, Any};
use std::borrow::Borrow;
use std::collections::HashMap;
use std::iter::empty;
use std::marker::PhantomData;
use std::ops::Deref;

/// Represents a service provider.
#[derive(Clone)]
pub struct ServiceProvider {
    services: Ref<HashMap<Type, Vec<ServiceDescriptor>>>,
}

#[cfg(feature = "async")]
unsafe impl Send for ServiceProvider {}

#[cfg(feature = "async")]
unsafe impl Sync for ServiceProvider {}

impl ServiceProvider {
    /// Initializes a new service provider.
    ///
    /// # Arguments
    ///
    /// * `services` - The [`ServiceDescriptor`](crate::ServiceDescriptor) map encapsulated by the provider
    pub fn new(services: HashMap<Type, Vec<ServiceDescriptor>>) -> Self {
        Self {
            services: Ref::new(services),
        }
    }

    /// Gets a service of the specified type.
    pub fn get<T: Any + ?Sized>(&self) -> Option<Ref<T>> {
        let key = Type::of::<T>();

        if let Some(descriptors) = self.services.get(&key) {
            if let Some(descriptor) = descriptors.last() {
                return Some(
                    descriptor
                        .get(self)
                        .downcast_ref::<Ref<T>>()
                        .unwrap()
                        .clone(),
                );
            }
        }

        None
    }

    /// Gets a mutable service of the specified type.
    pub fn get_mut<T: Any + ?Sized>(&self) -> Option<RefMut<T>> {
        self.get::<Mut<T>>()
    }

    /// Gets a keyed service of the specified type.
    pub fn get_by_key<TKey, TSvc: Any + ?Sized>(&self) -> Option<KeyedRef<TKey, TSvc>> {
        let key = Type::keyed::<TKey, TSvc>();

        if let Some(descriptors) = self.services.get(&key) {
            if let Some(descriptor) = descriptors.last() {
                return Some(KeyedRef::new(
                    descriptor
                        .get(self)
                        .downcast_ref::<Ref<TSvc>>()
                        .unwrap()
                        .clone(),
                ));
            }
        }

        None
    }

    /// Gets a keyed, mutable service of the specified type.
    pub fn get_by_key_mut<TKey, TSvc: Any + ?Sized>(
        &self,
    ) -> Option<KeyedRefMut<TKey, TSvc>> {
        self.get_by_key::<TKey, Mut<TSvc>>()
    }

    /// Gets all of the services of the specified type.
    pub fn get_all<T: Any + ?Sized>(&self) -> impl Iterator<Item = Ref<T>> + '_ {
        let key = Type::of::<T>();

        if let Some(descriptors) = self.services.get(&key) {
            ServiceIterator::new(self, descriptors.iter())
        } else {
            ServiceIterator::new(self, empty())
        }
    }

    /// Gets all of the mutable services of the specified type.
    pub fn get_all_mut<T: Any + ?Sized>(&self) -> impl Iterator<Item = RefMut<T>> + '_ {
        self.get_all::<Mut<T>>()
    }

    /// Gets all of the services of the specified key and type.
    pub fn get_all_by_key<'a, TKey: 'a, TSvc>(
        &'a self,
    ) -> impl Iterator<Item = KeyedRef<TKey, TSvc>> + '_
    where
        TSvc: Any + ?Sized,
    {
        let key = Type::keyed::<TKey, TSvc>();

        if let Some(descriptors) = self.services.get(&key) {
            KeyedServiceIterator::new(self, descriptors.iter())
        } else {
            KeyedServiceIterator::new(self, empty())
        }
    }

    /// Gets all of the mutable services of the specified key and type.
    pub fn get_all_by_key_mut<'a, TKey: 'a, TSvc>(
        &'a self,
    ) -> impl Iterator<Item = KeyedRefMut<TKey, TSvc>> + '_
    where
        TSvc: Any + ?Sized,
    {
        self.get_all_by_key::<TKey, Mut<TSvc>>()
    }

    /// Gets a required service of the specified type.
    ///
    /// # Panics
    ///
    /// The requested service of type `T` does not exist.
    pub fn get_required<T: Any + ?Sized>(&self) -> Ref<T> {
        if let Some(service) = self.get::<T>() {
            service
        } else {
            panic!(
                "No service for type '{}' has been registered.",
                type_name::<T>()
            );
        }
    }

    /// Gets a required, mutable service of the specified type.
    ///
    /// # Panics
    ///
    /// The requested service of type `T` does not exist.
    pub fn get_required_mut<T: Any + ?Sized>(&self) -> RefMut<T> {
        self.get_required::<Mut<T>>()
    }

    /// Gets a required keyed service of the specified type.
    ///
    /// # Panics
    ///
    /// The requested service of type `TSvc` with key `TKey` does not exist.
    pub fn get_required_by_key<TKey, TSvc: Any + ?Sized>(&self) -> KeyedRef<TKey, TSvc> {
        if let Some(service) = self.get_by_key::<TKey, TSvc>() {
            service
        } else {
            panic!(
                "No service for type '{}' with the key '{}' has been registered.",
                type_name::<TSvc>(),
                type_name::<TKey>()
            );
        }
    }

    /// Gets a required keyed service of the specified type.
    ///
    /// # Panics
    ///
    /// The requested service of type `TSvc` with key `TKey` does not exist.
    pub fn get_required_by_key_mut<TKey, TSvc: Any + ?Sized>(
        &self,
    ) -> KeyedRefMut<TKey, TSvc> {
        self.get_required_by_key::<TKey, Mut<TSvc>>()
    }

    /// Creates and returns a new service provider that is used to resolve
    /// services from a newly create scope.
    pub fn create_scope(&self) -> Self {
        Self::new(self.services.as_ref().clone())
    }
}

/// Represents a scoped [`ServiceProvider`].
/// 
/// # Remarks
/// 
/// This struct has the exact same functionality as [`ServiceProvider`](crate::ServiceProvider).
/// When a new instance is created, it also creates a new scope from the source
/// [`ServiceProvider`](crate::ServiceProvider). The primary use case for this struct is to
/// explicitly declare that a new scope should be created at the injection call site.
#[derive(Clone, Default)]
pub struct ScopedServiceProvider {
    sp: ServiceProvider
}

impl From<&ServiceProvider> for ScopedServiceProvider {
    fn from(value: &ServiceProvider) -> Self {
        Self { sp: value.create_scope() }
    }
}

impl AsRef<ServiceProvider> for ScopedServiceProvider {
    fn as_ref(&self) -> &ServiceProvider {
        &self.sp
    }
}

impl Borrow<ServiceProvider> for ScopedServiceProvider {
    fn borrow(&self) -> &ServiceProvider {
        &self.sp
    }
}

impl Deref for ScopedServiceProvider {
    type Target = ServiceProvider;

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

struct ServiceIterator<'a, T>
where
    T: Any + ?Sized,
{
    provider: &'a ServiceProvider,
    descriptors: Box<dyn Iterator<Item = &'a ServiceDescriptor> + 'a>,
    _marker: PhantomData<T>,
}

struct KeyedServiceIterator<'a, TKey, TSvc>
where
    TSvc: Any + ?Sized,
{
    provider: &'a ServiceProvider,
    descriptors: Box<dyn Iterator<Item = &'a ServiceDescriptor> + 'a>,
    _key: PhantomData<TKey>,
    _svc: PhantomData<TSvc>,
}

impl<'a, T: Any + ?Sized> ServiceIterator<'a, T> {
    fn new<I>(provider: &'a ServiceProvider, descriptors: I) -> Self
    where
        I: Iterator<Item = &'a ServiceDescriptor> + 'a,
    {
        Self {
            provider,
            descriptors: Box::new(descriptors),
            _marker: PhantomData,
        }
    }
}

impl<'a, T: Any + ?Sized> Iterator for ServiceIterator<'a, T> {
    type Item = Ref<T>;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(descriptor) = self.descriptors.next() {
            Some(
                descriptor
                    .get(self.provider)
                    .downcast_ref::<Ref<T>>()
                    .unwrap()
                    .clone(),
            )
        } else {
            None
        }
    }
}

impl<'a, TKey, TSvc: Any + ?Sized> KeyedServiceIterator<'a, TKey, TSvc> {
    fn new<I>(provider: &'a ServiceProvider, descriptors: I) -> Self
    where
        I: Iterator<Item = &'a ServiceDescriptor> + 'a,
    {
        Self {
            provider,
            descriptors: Box::new(descriptors),
            _key: PhantomData,
            _svc: PhantomData,
        }
    }
}

impl<'a, TKey, TSvc: Any + ?Sized> Iterator for KeyedServiceIterator<'a, TKey, TSvc> {
    type Item = KeyedRef<TKey, TSvc>;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(descriptor) = self.descriptors.next() {
            Some(KeyedRef::new(
                descriptor
                    .get(self.provider)
                    .downcast_ref::<Ref<TSvc>>()
                    .unwrap()
                    .clone(),
            ))
        } else {
            None
        }
    }
}

impl Default for ServiceProvider {
    fn default() -> Self {
        Self {
            services: Ref::new(HashMap::with_capacity(0)),
        }
    }
}

#[cfg(test)]
mod tests {

    use crate::{test::*, *};
    use std::fs::remove_file;
    use std::path::{Path, PathBuf};

    #[cfg(feature = "async")]
    use std::sync::{Arc, Mutex};

    #[cfg(feature = "async")]
    use std::thread;

    #[test]
    fn get_should_return_none_when_service_is_unregistered() {
        // arrange
        let services = ServiceCollection::new().build_provider().unwrap();

        // act
        let result = services.get::<dyn TestService>();

        // assert
        assert!(result.is_none());
    }

    #[test]
    fn get_by_key_should_return_none_when_service_is_unregistered() {
        // arrange
        let services = ServiceCollection::new().build_provider().unwrap();

        // act
        let result = services.get_by_key::<key::Thingy, dyn TestService>();

        // assert
        assert!(result.is_none());
    }

    #[test]
    fn get_should_return_registered_service() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                singleton::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl::default())),
            )
            .build_provider()
            .unwrap();

        // act
        let result = services.get::<dyn TestService>();

        // assert
        assert!(result.is_some());
    }

    #[test]
    fn get_by_key_should_return_registered_service() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                singleton_with_key::<key::Thingy, dyn Thing, Thing1>()
                    .from(|_| Ref::new(Thing1::default())),
            )
            .add(singleton::<dyn Thing, Thing1>().from(|_| Ref::new(Thing1::default())))
            .build_provider()
            .unwrap();

        // act
        let result = services.get_by_key::<key::Thingy, dyn Thing>();

        // assert
        assert!(result.is_some());
    }

    #[test]
    fn get_required_should_return_registered_service() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                singleton::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl::default())),
            )
            .build_provider()
            .unwrap();

        // act
        let _ = services.get_required::<dyn TestService>();

        // assert
        // didn't panic
    }

    #[test]
    fn get_required_by_key_should_return_registered_service() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                singleton_with_key::<key::Thingy, dyn Thing, Thing3>()
                    .from(|_| Ref::new(Thing3::default())),
            )
            .add(singleton::<dyn Thing, Thing1>().from(|_| Ref::new(Thing1::default())))
            .build_provider()
            .unwrap();

        // act
        let thing = services.get_required_by_key::<key::Thingy, dyn Thing>();

        // assert
        assert_eq!(&thing.to_string(), "di::test::Thing3");
    }

    #[test]
    #[should_panic(
        expected = "No service for type 'dyn di::test::TestService' has been registered."
    )]
    fn get_required_should_panic_when_service_is_unregistered() {
        // arrange
        let services = ServiceCollection::new().build_provider().unwrap();

        // act
        let _ = services.get_required::<dyn TestService>();

        // assert
        // panics
    }

    #[test]
    #[should_panic(
        expected = "No service for type 'dyn di::test::Thing' with the key 'di::test::key::Thing1' has been registered."
    )]
    fn get_required_by_key_should_panic_when_service_is_unregistered() {
        // arrange
        let services = ServiceCollection::new().build_provider().unwrap();

        // act
        let _ = services.get_required_by_key::<key::Thing1, dyn Thing>();

        // assert
        // panics
    }

    #[test]
    #[allow(clippy::vtable_address_comparisons)]
    fn get_should_return_same_instance_for_singleton_service() {
        // arrange
        let services = ServiceCollection::new()
            .add(existing::<dyn TestService, TestServiceImpl>(Box::new(
                TestServiceImpl::default(),
            )))
            .add(
                singleton::<dyn OtherTestService, OtherTestServiceImpl>().from(|sp| {
                    Ref::new(OtherTestServiceImpl::new(
                        sp.get_required::<dyn TestService>(),
                    ))
                }),
            )
            .build_provider()
            .unwrap();

        // act
        let svc2 = services.get_required::<dyn OtherTestService>();
        let svc1 = services.get_required::<dyn OtherTestService>();

        // assert
        assert!(Ref::ptr_eq(&svc1, &svc2));
    }

    #[test]
    #[allow(clippy::vtable_address_comparisons)]
    fn get_should_return_different_instances_for_transient_service() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                transient::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl::default())),
            )
            .build_provider()
            .unwrap();

        // act
        let svc1 = services.get_required::<dyn TestService>();
        let svc2 = services.get_required::<dyn TestService>();

        // assert
        assert!(!Ref::ptr_eq(&svc1, &svc2));
    }

    #[test]
    fn get_all_should_return_all_services() {
        // arrange
        let mut collection = ServiceCollection::new();

        collection
            .add(
                singleton::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl { value: 1 })),
            )
            .add(
                singleton::<dyn TestService, TestService2Impl>()
                    .from(|_| Ref::new(TestService2Impl { value: 2 })),
            );

        let provider = collection.build_provider().unwrap();

        // act
        let services = provider.get_all::<dyn TestService>();
        let values: Vec<_> = services.map(|s| s.value()).collect();

        // assert
        assert_eq!(&values, &[1, 2]);
    }

    #[test]
    fn get_all_by_key_should_return_all_services() {
        // arrange
        let mut collection = ServiceCollection::new();

        collection
            .add(
                singleton_with_key::<key::Thingies, dyn Thing, Thing1>()
                    .from(|_| Ref::new(Thing1::default())),
            )
            .add(
                singleton_with_key::<key::Thingies, dyn Thing, Thing2>()
                    .from(|_| Ref::new(Thing2::default())),
            )
            .add(
                singleton_with_key::<key::Thingies, dyn Thing, Thing3>()
                    .from(|_| Ref::new(Thing3::default())),
            );

        let provider = collection.build_provider().unwrap();

        // act
        let services = provider.get_all_by_key::<key::Thingies, dyn Thing>();
        let values: Vec<_> = services.map(|s| s.to_string()).collect();

        // assert
        assert_eq!(
            &values,
            &[
                "di::test::Thing1".to_owned(),
                "di::test::Thing2".to_owned(),
                "di::test::Thing3".to_owned()
            ]
        );
    }

    #[test]
    #[allow(clippy::vtable_address_comparisons)]
    fn two_scoped_service_providers_should_create_different_instances() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                scoped::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl::default())),
            )
            .build_provider()
            .unwrap();
        let scope1 = services.create_scope();
        let scope2 = services.create_scope();

        // act
        let svc1 = scope1.get_required::<dyn TestService>();
        let svc2 = scope2.get_required::<dyn TestService>();

        // assert
        assert!(!Ref::ptr_eq(&svc1, &svc2));
    }

    #[test]
    #[allow(clippy::vtable_address_comparisons)]
    fn parent_child_scoped_service_providers_should_create_different_instances() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                scoped::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl::default())),
            )
            .build_provider()
            .unwrap();
        let scope1 = services.create_scope();
        let scope2 = scope1.create_scope();

        // act
        let svc1 = scope1.get_required::<dyn TestService>();
        let svc2 = scope2.get_required::<dyn TestService>();

        // assert
        assert!(!Ref::ptr_eq(&svc1, &svc2));
    }

    #[test]
    #[allow(clippy::vtable_address_comparisons)]
    fn scoped_service_provider_should_have_same_singleton_when_eager_created_in_parent() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                singleton::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl::default())),
            )
            .build_provider()
            .unwrap();
        let svc1 = services.get_required::<dyn TestService>();
        let scope1 = services.create_scope();
        let scope2 = scope1.create_scope();

        // act
        let svc2 = scope1.get_required::<dyn TestService>();
        let svc3 = scope2.get_required::<dyn TestService>();

        // assert
        assert!(Ref::ptr_eq(&svc1, &svc2));
        assert!(Ref::ptr_eq(&svc1, &svc3));
    }

    #[test]
    #[allow(clippy::vtable_address_comparisons)]
    fn scoped_service_provider_should_have_same_singleton_when_lazy_created_in_parent() {
        // arrange
        let services = ServiceCollection::new()
            .add(
                singleton::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl::default())),
            )
            .build_provider()
            .unwrap();
        let scope1 = services.create_scope();
        let scope2 = scope1.create_scope();
        let svc1 = services.get_required::<dyn TestService>();

        // act
        let svc2 = scope1.get_required::<dyn TestService>();
        let svc3 = scope2.get_required::<dyn TestService>();

        // assert
        assert!(Ref::ptr_eq(&svc1, &svc2));
        assert!(Ref::ptr_eq(&svc1, &svc3));
    }

    #[test]
    fn service_provider_should_drop_existing_as_service() {
        // arrange
        let file = new_temp_file("drop2");

        // act
        {
            let mut services = ServiceCollection::new();
            services.add(existing_as_self(Droppable::new(file.clone())));
            let _ = services.build_provider().unwrap();
        }

        // assert
        let dropped = !file.exists();
        remove_file(&file).ok();
        assert!(dropped);
    }

    #[test]
    fn service_provider_should_drop_lazy_initialized_service() {
        // arrange
        let file = new_temp_file("drop3");

        // act
        {
            let provider = ServiceCollection::new()
                .add(existing::<Path, PathBuf>(file.clone().into_boxed_path()))
                .add(singleton_as_self().from(|sp| {
                    Ref::new(Droppable::new(sp.get_required::<Path>().to_path_buf()))
                }))
                .build_provider()
                .unwrap();
            let _ = provider.get_required::<Droppable>();
        }

        // assert
        let dropped = !file.exists();
        remove_file(&file).ok();
        assert!(dropped);
    }

    #[test]
    fn service_provider_should_not_drop_service_if_never_instantiated() {
        // arrange
        let file = new_temp_file("drop5");

        // act
        {
            let _ = ServiceCollection::new()
                .add(existing::<Path, PathBuf>(file.clone().into_boxed_path()))
                .add(singleton_as_self().from(|sp| {
                    Ref::new(Droppable::new(sp.get_required::<Path>().to_path_buf()))
                }))
                .build_provider()
                .unwrap();
        }

        // assert
        let not_dropped = file.exists();
        remove_file(&file).ok();
        assert!(not_dropped);
    }

    #[test]
    #[allow(clippy::vtable_address_comparisons)]
    fn clone_should_be_shallow() {
        // arrange
        let provider1 = ServiceCollection::new()
            .add(
                transient::<dyn TestService, TestServiceImpl>()
                    .from(|_| Ref::new(TestServiceImpl::default())),
            )
            .build_provider()
            .unwrap();

        // act
        let provider2 = provider1.clone();

        // assert
        assert!(Ref::ptr_eq(&provider1.services, &provider2.services));
        assert!(std::ptr::eq(
            provider1.services.as_ref(),
            provider2.services.as_ref()
        ));
    }

    #[cfg(feature = "async")]
    #[derive(Clone)]
    struct Holder<T: Send + Sync + Clone>(T);

    #[cfg(feature = "async")]
    fn inject<V: Send + Sync + Clone>(value: V) -> Holder<V> {
        Holder(value)
    }

    #[test]
    #[cfg(feature = "async")]
    fn service_provider_should_be_async_safe() {
        // arrange
        let provider = ServiceCollection::new()
            .add(
                singleton::<dyn TestService, TestAsyncServiceImpl>()
                    .from(|_| Ref::new(TestAsyncServiceImpl::default())),
            )
            .build_provider()
            .unwrap();
        let holder = inject(provider);
        let h1 = holder.clone();
        let h2 = holder.clone();
        let value = Arc::new(Mutex::new(0));
        let v1 = value.clone();
        let v2 = value.clone();

        // act
        let t1 = thread::spawn(move || {
            let service = h1.0.get_required::<dyn TestService>();
            let mut result = v1.lock().unwrap();
            *result += service.value();
        });

        let t2 = thread::spawn(move || {
            let service = h2.0.get_required::<dyn TestService>();
            let mut result = v2.lock().unwrap();
            *result += service.value();
        });

        t1.join().ok();
        t2.join().ok();

        // assert
        assert_eq!(*value.lock().unwrap(), 3);
    }
}