Skip to main content

deorbit_core/builder/
services.rs

1use crate::Services;
2use crate::builder::alias::AliasBuilder;
3use crate::builder::concrete::ConcreteBuilder;
4use crate::builder::{Binding, BindingKind, BindingLifetime};
5use crate::resolver::Error;
6use crate::runtime::{ErasedUnsizer, TypeMeta};
7
8/// A builder for Services.
9#[derive(Default, Debug)]
10pub struct ServicesBuilder {
11    bindings: Vec<Binding>,
12}
13
14impl ServicesBuilder {
15    pub fn new() -> Self {
16        Self { bindings: vec![] }
17    }
18
19    pub fn build(self) -> Result<Services, Error> {
20        Services::from_builder(self)
21    }
22
23    /// Binds a service using automatic instantiation.
24    pub fn bind<T: 'static>(&mut self) -> ConcreteBuilder<'_, T> {
25        ConcreteBuilder::from_builder(self)
26    }
27
28    pub fn bind_alias<T: ?Sized + Send + Sync + 'static>(&mut self) -> AliasBuilder<'_, T> {
29        AliasBuilder::from_builder(self)
30    }
31
32    pub(crate) fn add_type_binding<T: 'static>(
33        &mut self,
34        bind_self: bool,
35        lifetime: BindingLifetime,
36        deps: &'static [TypeMeta],
37    ) {
38        let binding = Binding {
39            ty: TypeMeta::of::<T>(),
40            kind: BindingKind::Type {
41                lifetime,
42                deps,
43                bind_self,
44            },
45        };
46
47        self.bindings.push(binding);
48    }
49
50    pub(crate) fn add_alias_binding<T: ?Sized + 'static>(
51        &mut self,
52        impls: Vec<(TypeMeta, ErasedUnsizer)>,
53    ) {
54        let binding = Binding {
55            ty: TypeMeta::of::<T>(),
56            kind: BindingKind::Alias { impls },
57        };
58
59        self.bindings.push(binding);
60    }
61
62    pub(crate) fn to_vec(self) -> Vec<Binding> {
63        self.bindings
64    }
65}