aboutsummaryrefslogtreecommitdiff
path: root/src/di_container/blocking/mod.rs
blob: 27ea0fb0727bd910473bdfc87c484439f795756d (plain)
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
//! Blocking dependency injection container.
//!
//! # Examples
//! ```
//! use std::collections::HashMap;
//! use std::error::Error;
//!
//! use syrette::di_container::blocking::IDIContainer;
//! use syrette::{injectable, DIContainer};
//!
//! trait IDatabaseService
//! {
//!     fn get_all_records(&self, table_name: String) -> HashMap<String, String>;
//! }
//!
//! struct DatabaseService {}
//!
//! #[injectable(IDatabaseService)]
//! impl DatabaseService
//! {
//!     fn new() -> Self
//!     {
//!         Self {}
//!     }
//! }
//!
//! impl IDatabaseService for DatabaseService
//! {
//!     fn get_all_records(&self, table_name: String) -> HashMap<String, String>
//!     {
//!         // Do stuff here
//!         HashMap::<String, String>::new()
//!     }
//! }
//!
//! fn main() -> Result<(), Box<dyn Error>>
//! {
//!     let mut di_container = DIContainer::new();
//!
//!     di_container
//!         .bind::<dyn IDatabaseService>()
//!         .to::<DatabaseService>()
//!         .map_err(|err| err.to_string())?;
//!
//!     let database_service = di_container
//!         .get::<dyn IDatabaseService>()
//!         .map_err(|err| err.to_string())?
//!         .transient()?;
//!
//!     Ok(())
//! }
//! ```
use std::any::type_name;
use std::cell::RefCell;
use std::rc::Rc;

use crate::di_container::binding_storage::DIContainerBindingStorage;
use crate::di_container::blocking::binding::builder::BindingBuilder;
use crate::di_container::BindingOptions;
use crate::errors::di_container::DIContainerError;
use crate::private::cast::boxed::CastBox;
use crate::private::cast::rc::CastRc;
use crate::provider::blocking::{IProvider, Providable};
use crate::ptr::SomePtr;
use crate::util::use_double;

use_double!(crate::dependency_history::DependencyHistory);

pub mod binding;
pub mod prelude;

/// Blocking dependency injection container interface.
///
/// **This trait is sealed and cannot be implemented for types outside this crate.**
pub trait IDIContainer: Sized + 'static + details::DIContainerInternals
{
    /// Returns a new [`BindingBuilder`] for the given interface.
    fn bind<Interface>(self: &mut Rc<Self>) -> BindingBuilder<Interface, Self>
    where
        Interface: 'static + ?Sized;

    /// Returns the type bound with `Interface`.
    ///
    /// # Errors
    /// Will return `Err` if:
    /// - No binding for `Interface` exists
    /// - Resolving the binding for `Interface` fails
    /// - Casting the binding for `Interface` fails
    fn get<Interface>(self: &Rc<Self>) -> Result<SomePtr<Interface>, DIContainerError>
    where
        Interface: 'static + ?Sized;

    /// Returns the type bound with `Interface` and the specified name.
    ///
    /// # Errors
    /// Will return `Err` if:
    /// - No binding for `Interface` with name `name` exists
    /// - Resolving the binding for `Interface` fails
    /// - Casting the binding for `Interface` fails
    fn get_named<Interface>(
        self: &Rc<Self>,
        name: &'static str,
    ) -> Result<SomePtr<Interface>, DIContainerError>
    where
        Interface: 'static + ?Sized;

    /// Returns the type bound with `Interface` where the binding has the specified
    /// options.
    ///
    /// `dependency_history` is passed to the bound type when it is being resolved.
    ///
    /// # Errors
    /// Will return `Err` if:
    /// - No binding for `Interface` exists
    /// - Resolving the binding for `Interface` fails
    /// - Casting the binding for `Interface` fails
    ///
    /// # Examples
    /// ```no_run
    /// # use syrette::di_container::blocking::DIContainer;
    /// # use syrette::di_container::blocking::IDIContainer;
    /// # use syrette::dependency_history::DependencyHistory;
    /// # use syrette::di_container::BindingOptions;
    /// #
    /// # struct EventHandler {}
    /// # struct Button {}
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let di_container = DIContainer::new();
    /// #
    /// let mut dependency_history = DependencyHistory::new();
    ///
    /// dependency_history.push::<EventHandler>();
    ///
    /// di_container.get_bound::<Button>(
    ///     dependency_history,
    ///     BindingOptions::new().name("huge_red"),
    /// )?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    fn get_bound<Interface>(
        self: &Rc<Self>,
        dependency_history: DependencyHistory,
        binding_options: BindingOptionsWithLt,
    ) -> Result<SomePtr<Interface>, DIContainerError>
    where
        Interface: 'static + ?Sized;
}

#[cfg(not(test))]
pub(crate) type BindingOptionsWithLt<'a> = BindingOptions<'a>;

#[cfg(test)]
pub(crate) type BindingOptionsWithLt = BindingOptions<'static>;

/// Blocking dependency injection container.
pub struct DIContainer
{
    binding_storage: RefCell<DIContainerBindingStorage<dyn IProvider<Self>>>,
}

impl DIContainer
{
    /// Returns a new `DIContainer`.
    #[must_use]
    pub fn new() -> Rc<Self>
    {
        Rc::new(Self {
            binding_storage: RefCell::new(DIContainerBindingStorage::new()),
        })
    }
}

impl IDIContainer for DIContainer
{
    fn bind<Interface>(self: &mut Rc<Self>) -> BindingBuilder<Interface, Self>
    where
        Interface: 'static + ?Sized,
    {
        BindingBuilder::new(self.clone(), DependencyHistory::new)
    }

    fn get<Interface>(self: &Rc<Self>) -> Result<SomePtr<Interface>, DIContainerError>
    where
        Interface: 'static + ?Sized,
    {
        self.get_bound::<Interface>(DependencyHistory::new(), BindingOptions::new())
    }

    fn get_named<Interface>(
        self: &Rc<Self>,
        name: &'static str,
    ) -> Result<SomePtr<Interface>, DIContainerError>
    where
        Interface: 'static + ?Sized,
    {
        self.get_bound::<Interface>(
            DependencyHistory::new(),
            BindingOptions::new().name(name),
        )
    }

    fn get_bound<Interface>(
        self: &Rc<Self>,
        dependency_history: DependencyHistory,
        binding_options: BindingOptions,
    ) -> Result<SomePtr<Interface>, DIContainerError>
    where
        Interface: 'static + ?Sized,
    {
        let binding_providable = self
            .get_binding_providable::<Interface>(binding_options, dependency_history)?;

        #[cfg(feature = "factory")]
        return self.handle_binding_providable(binding_providable);

        #[cfg(not(feature = "factory"))]
        Self::handle_binding_providable(binding_providable)
    }
}

impl details::DIContainerInternals for DIContainer
{
    fn has_binding<Interface>(self: &Rc<Self>, binding_options: BindingOptions) -> bool
    where
        Interface: ?Sized + 'static,
    {
        self.binding_storage
            .borrow()
            .has::<Interface>(binding_options)
    }

    fn set_binding<Interface>(
        self: &Rc<Self>,
        binding_options: BindingOptions<'static>,
        provider: Box<dyn IProvider<Self>>,
    ) where
        Interface: 'static + ?Sized,
    {
        self.binding_storage
            .borrow_mut()
            .set::<Interface>(binding_options, provider);
    }

    fn remove_binding<Interface>(
        self: &Rc<Self>,
        binding_options: BindingOptions<'static>,
    ) -> Option<Box<dyn IProvider<Self>>>
    where
        Interface: 'static + ?Sized,
    {
        self.binding_storage
            .borrow_mut()
            .remove::<Interface>(binding_options)
    }
}

impl DIContainer
{
    fn handle_binding_providable<Interface>(
        #[cfg(feature = "factory")] self: &Rc<Self>,
        binding_providable: Providable<Self>,
    ) -> Result<SomePtr<Interface>, DIContainerError>
    where
        Interface: 'static + ?Sized,
    {
        match binding_providable {
            Providable::Transient(transient_binding) => Ok(SomePtr::Transient(
                transient_binding.cast::<Interface>().map_err(|_| {
                    DIContainerError::CastFailed {
                        interface: type_name::<Interface>(),
                        binding_kind: "transient",
                    }
                })?,
            )),
            Providable::Singleton(singleton_binding) => Ok(SomePtr::Singleton(
                singleton_binding.cast::<Interface>().map_err(|_| {
                    DIContainerError::CastFailed {
                        interface: type_name::<Interface>(),
                        binding_kind: "singleton",
                    }
                })?,
            )),
            #[cfg(feature = "factory")]
            Providable::Factory(factory_binding) => {
                use crate::private::factory::IFactory;

                let factory = factory_binding
                    .cast::<dyn IFactory<(Rc<DIContainer>,), Interface>>()
                    .map_err(|_| DIContainerError::CastFailed {
                        interface: type_name::<Interface>(),
                        binding_kind: "factory",
                    })?;

                Ok(SomePtr::Factory(factory(self.clone()).into()))
            }
            #[cfg(feature = "factory")]
            Providable::DefaultFactory(factory_binding) => {
                use crate::private::factory::IFactory;
                use crate::ptr::TransientPtr;

                let default_factory = factory_binding
                    .cast::<dyn IFactory<
                        (Rc<DIContainer>,),
                        dyn Fn<(), Output = TransientPtr<Interface>>,
                    >>()
                    .map_err(|_| DIContainerError::CastFailed {
                        interface: type_name::<Interface>(),
                        binding_kind: "default factory",
                    })?;

                Ok(SomePtr::Transient(default_factory(self.clone())()))
            }
        }
    }

    fn get_binding_providable<Interface>(
        self: &Rc<Self>,
        binding_options: BindingOptions,
        dependency_history: DependencyHistory,
    ) -> Result<Providable<Self>, DIContainerError>
    where
        Interface: 'static + ?Sized,
    {
        let name = binding_options.name;

        self.binding_storage
            .borrow()
            .get::<Interface>(binding_options)
            .map_or_else(
                || {
                    Err(DIContainerError::BindingNotFound {
                        interface: type_name::<Interface>(),
                        name: name.as_ref().map(ToString::to_string),
                    })
                },
                Ok,
            )?
            .provide(self, dependency_history)
            .map_err(|err| DIContainerError::BindingResolveFailed {
                reason: err,
                interface: type_name::<Interface>(),
            })
    }
}

pub(crate) mod details
{
    use std::rc::Rc;

    use crate::di_container::blocking::BindingOptionsWithLt;
    use crate::di_container::BindingOptions;
    use crate::provider::blocking::IProvider;

    pub trait DIContainerInternals
    {
        fn has_binding<Interface>(
            self: &Rc<Self>,
            binding_options: BindingOptionsWithLt,
        ) -> bool
        where
            Interface: ?Sized + 'static;

        fn set_binding<Interface>(
            self: &Rc<Self>,
            binding_options: BindingOptions<'static>,
            provider: Box<dyn IProvider<Self>>,
        ) where
            Interface: 'static + ?Sized;

        fn remove_binding<Interface>(
            self: &Rc<Self>,
            binding_options: BindingOptions<'static>,
        ) -> Option<Box<dyn IProvider<Self>>>
        where
            Interface: 'static + ?Sized;
    }
}

#[cfg(test)]
mod tests
{
    use std::error::Error;

    use super::*;
    use crate::ptr::{SingletonPtr, TransientPtr};
    use crate::test_utils::{mocks, subjects};

    #[test]
    fn can_get() -> Result<(), Box<dyn Error>>
    {
        let di_container = DIContainer::new();

        let mut mock_provider = mocks::blocking_provider::MockProvider::new();

        mock_provider.expect_provide().returning(|_, _| {
            Ok(Providable::Transient(TransientPtr::new(
                subjects::UserManager::new(),
            )))
        });

        di_container
            .binding_storage
            .borrow_mut()
            .set::<dyn subjects::IUserManager>(
                BindingOptions::new(),
                Box::new(mock_provider),
            );

        di_container
            .get::<dyn subjects::IUserManager>()?
            .transient()?;

        Ok(())
    }

    #[test]
    fn can_get_named() -> Result<(), Box<dyn Error>>
    {
        let di_container = DIContainer::new();

        let mut mock_provider = mocks::blocking_provider::MockProvider::new();

        mock_provider.expect_provide().returning(|_, _| {
            Ok(Providable::Transient(TransientPtr::new(
                subjects::UserManager::new(),
            )))
        });

        di_container
            .binding_storage
            .borrow_mut()
            .set::<dyn subjects::IUserManager>(
                BindingOptions::new().name("special"),
                Box::new(mock_provider),
            );

        di_container
            .get_named::<dyn subjects::IUserManager>("special")?
            .transient()?;

        Ok(())
    }

    #[test]
    fn can_get_singleton() -> Result<(), Box<dyn Error>>
    {
        let di_container = DIContainer::new();

        let mut mock_provider = mocks::blocking_provider::MockProvider::new();

        let mut singleton = SingletonPtr::new(subjects::Number::new());

        SingletonPtr::get_mut(&mut singleton).unwrap().num = 2820;

        mock_provider
            .expect_provide()
            .returning_st(move |_, _| Ok(Providable::Singleton(singleton.clone())));

        di_container
            .binding_storage
            .borrow_mut()
            .set::<dyn subjects::INumber>(BindingOptions::new(), Box::new(mock_provider));

        let first_number_rc = di_container.get::<dyn subjects::INumber>()?.singleton()?;

        assert_eq!(first_number_rc.get(), 2820);

        let second_number_rc =
            di_container.get::<dyn subjects::INumber>()?.singleton()?;

        assert_eq!(first_number_rc.as_ref(), second_number_rc.as_ref());

        Ok(())
    }

    #[test]
    fn can_get_singleton_named() -> Result<(), Box<dyn Error>>
    {
        let di_container = DIContainer::new();

        let mut mock_provider = mocks::blocking_provider::MockProvider::new();

        let mut singleton = SingletonPtr::new(subjects::Number::new());

        SingletonPtr::get_mut(&mut singleton).unwrap().num = 2820;

        mock_provider
            .expect_provide()
            .returning_st(move |_, _| Ok(Providable::Singleton(singleton.clone())));

        di_container
            .binding_storage
            .borrow_mut()
            .set::<dyn subjects::INumber>(
                BindingOptions::new().name("cool"),
                Box::new(mock_provider),
            );

        let first_number_rc = di_container
            .get_named::<dyn subjects::INumber>("cool")?
            .singleton()?;

        assert_eq!(first_number_rc.get(), 2820);

        let second_number_rc = di_container
            .get_named::<dyn subjects::INumber>("cool")?
            .singleton()?;

        assert_eq!(first_number_rc.as_ref(), second_number_rc.as_ref());

        Ok(())
    }

    #[test]
    #[cfg(feature = "factory")]
    fn can_get_factory() -> Result<(), Box<dyn Error>>
    {
        use crate::private::castable_factory::blocking::CastableFactory;
        use crate::ptr::FactoryPtr;

        trait IUserManager
        {
            fn add_user(&mut self, user_id: i128);

            fn remove_user(&mut self, user_id: i128);
        }

        struct UserManager
        {
            users: Vec<i128>,
        }

        impl UserManager
        {
            fn new(users: Vec<i128>) -> Self
            {
                Self { users }
            }
        }

        impl IUserManager for UserManager
        {
            fn add_user(&mut self, user_id: i128)
            {
                self.users.push(user_id);
            }

            fn remove_user(&mut self, user_id: i128)
            {
                let user_index =
                    self.users.iter().position(|user| *user == user_id).unwrap();

                self.users.remove(user_index);
            }
        }

        use crate as syrette;

        #[crate::factory]
        type IUserManagerFactory = dyn Fn(Vec<i128>) -> TransientPtr<dyn IUserManager>;

        let di_container = DIContainer::new();

        let factory_func: &dyn Fn(Rc<DIContainer>) -> Box<IUserManagerFactory> =
            &|_: Rc<DIContainer>| {
                Box::new(move |users| {
                    let user_manager: TransientPtr<dyn IUserManager> =
                        TransientPtr::new(UserManager::new(users));

                    user_manager
                })
            };

        let mut mock_provider = mocks::blocking_provider::MockProvider::new();

        mock_provider.expect_provide().returning_st(|_, _| {
            Ok(Providable::Factory(FactoryPtr::new(CastableFactory::new(
                factory_func,
            ))))
        });

        di_container
            .binding_storage
            .borrow_mut()
            .set::<IUserManagerFactory>(BindingOptions::new(), Box::new(mock_provider));

        di_container.get::<IUserManagerFactory>()?.factory()?;

        Ok(())
    }

    #[test]
    #[cfg(feature = "factory")]
    fn can_get_factory_named() -> Result<(), Box<dyn Error>>
    {
        use crate::private::castable_factory::blocking::CastableFactory;
        use crate::ptr::FactoryPtr;

        trait IUserManager
        {
            fn add_user(&mut self, user_id: i128);

            fn remove_user(&mut self, user_id: i128);
        }

        struct UserManager
        {
            users: Vec<i128>,
        }

        impl UserManager
        {
            fn new(users: Vec<i128>) -> Self
            {
                Self { users }
            }
        }

        impl IUserManager for UserManager
        {
            fn add_user(&mut self, user_id: i128)
            {
                self.users.push(user_id);
            }

            fn remove_user(&mut self, user_id: i128)
            {
                let user_index =
                    self.users.iter().position(|user| *user == user_id).unwrap();

                self.users.remove(user_index);
            }
        }

        use crate as syrette;

        #[crate::factory]
        type IUserManagerFactory = dyn Fn(Vec<i128>) -> TransientPtr<dyn IUserManager>;

        let di_container = DIContainer::new();

        let factory_func: &dyn Fn(Rc<DIContainer>) -> Box<IUserManagerFactory> =
            &|_: Rc<DIContainer>| {
                Box::new(move |users| {
                    let user_manager: TransientPtr<dyn IUserManager> =
                        TransientPtr::new(UserManager::new(users));

                    user_manager
                })
            };

        let mut mock_provider = mocks::blocking_provider::MockProvider::new();

        mock_provider.expect_provide().returning_st(|_, _| {
            Ok(Providable::Factory(FactoryPtr::new(CastableFactory::new(
                factory_func,
            ))))
        });

        di_container
            .binding_storage
            .borrow_mut()
            .set::<IUserManagerFactory>(
                BindingOptions::new().name("special"),
                Box::new(mock_provider),
            );

        di_container
            .get_named::<IUserManagerFactory>("special")?
            .factory()?;

        Ok(())
    }
}