di/
inject_builder.rs

1use crate::{Activator, ServiceDependency, Type, ServiceLifetime, ServiceDescriptor};
2use spin::Once;
3
4/// Represents the builder for an injected type.
5pub struct InjectBuilder {
6    activator: Activator,
7    lifetime: ServiceLifetime,
8    key_type: Option<Type>,
9    dependencies: Vec<ServiceDependency>,
10}
11
12impl InjectBuilder {
13    /// Initializes a new builder.
14    ///
15    /// # Arguments
16    ///
17    /// * `activator` - The [activator](crate::Activator) used to activate the service
18    /// * `lifetime` - The [lifetime](crate::ServiceLifetime) of the service
19    pub fn new(activator: Activator, lifetime: ServiceLifetime) -> Self {
20        Self {
21            activator,
22            lifetime,
23            key_type: None,
24            dependencies: Vec::default(),
25        }
26    }
27
28    /// Defines a dependency used by the service.
29    ///
30    /// # Arguments
31    ///
32    /// * `dependency` - The [dependency](crate::ServiceDependency) associated with the services
33    pub fn depends_on(mut self, dependency: ServiceDependency) -> Self {
34        if !self.dependencies.contains(&dependency) {
35            self.dependencies.push(dependency);
36        }
37        self
38    }
39
40    /// Applies a key to the injected service.
41    pub fn with_key<TKey>(mut self) -> Self {
42        self.key_type = Some(Type::of::<TKey>());
43        self
44    }
45
46    /// Indicates the injected service is mutable.
47    pub fn as_mut(mut self) -> Self {
48        self.activator.as_mut();
49        self
50    }
51
52    /// Builds and returns a new [`ServiceDescriptor`](crate::ServiceDescriptor).
53    pub fn build(mut self) -> ServiceDescriptor {
54        ServiceDescriptor::new(
55            self.lifetime,
56            if let Some(key) = self.key_type {
57                self.activator.service_type().with_key(&key)
58            } else {
59                self.activator.service_type().clone()
60            },
61            self.activator.implementation_type().clone(),
62            if self.dependencies.is_empty() {
63                Vec::with_capacity(0)
64            } else {
65                self.dependencies.shrink_to_fit();
66                self.dependencies
67            },
68            Once::new(),
69            self.activator.factory(),
70        )
71    }
72}
73
74impl From<InjectBuilder> for ServiceDescriptor {
75    fn from(value: InjectBuilder) -> Self {
76        value.build()
77    }
78}