di/
activator.rs

1use crate::{Mut, Ref, RefMut, ServiceFactory, ServiceProvider, Type};
2use std::any::Any;
3
4/// Represents an activator for a service instance.
5pub struct Activator {
6    service_type: Type,
7    service_type_mut: Type,
8    implementation_type: Type,
9    factory: Ref<ServiceFactory>,
10    factory_mut: Ref<ServiceFactory>,
11    mutable: bool,
12}
13
14impl Activator {
15    /// Gets the [service type](crate::Type) associated with the service descriptor.
16    pub fn service_type(&self) -> &Type {
17        if self.mutable {
18            &self.service_type_mut
19        } else {
20            &self.service_type
21        }
22    }
23
24    /// Gets the [implementation type](crate::Type) associated with the service descriptor.
25    pub fn implementation_type(&self) -> &Type {
26        &self.implementation_type
27    }
28
29    /// Sets a value indicating whether the activated instance should be mutable.
30    pub fn as_mut(&mut self) {
31        self.mutable = true;
32    }
33
34    /// Gets the factory method the activator represents.
35    pub fn factory(&self) -> Ref<ServiceFactory> {
36        if self.mutable {
37            self.factory_mut.clone()
38        } else {
39            self.factory.clone()
40        }
41    }
42
43    /// Creates a new activator using the specified factory methods to instantiate the service.
44    ///
45    /// # Arguments
46    ///
47    /// * `factory` - The factory method used to create a service instance
48    /// * `factory_mut` - The factory method used to create a mutable service instance
49    pub fn new<TSvc: Any + ?Sized, TImpl>(
50        factory: fn(&ServiceProvider) -> Ref<TSvc>,
51        factory_mut: fn(&ServiceProvider) -> RefMut<TSvc>,
52    ) -> Self {
53        Self {
54            service_type: Type::of::<TSvc>(),
55            service_type_mut: Type::of::<Mut<TSvc>>(),
56            implementation_type: Type::of::<TImpl>(),
57            factory: Ref::new(move |sp| Ref::new(factory(sp))),
58            factory_mut: Ref::new(move |sp| Ref::new(factory_mut(sp))),
59            mutable: false,
60        }
61    }
62}