Skip to main content

serenade_di/
definition.rs

1//! Service scope and definition metadata.
2
3use crate::Reference;
4
5/// Lifetime of a resolved service instance.
6#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
7pub enum Scope {
8    /// One shared instance for the container lifetime.
9    Singleton,
10    /// Fresh instance on every resolve.
11    Prototype,
12}
13
14/// Registered service definition before and after compile.
15#[derive(Clone, Debug)]
16pub struct ServiceDefinition {
17    id: String,
18    scope: Scope,
19    dependencies: Vec<Reference>,
20    tags: Vec<String>,
21}
22
23impl ServiceDefinition {
24    /// Creates a singleton definition with no declared dependencies.
25    #[must_use]
26    pub fn new(id: impl Into<String>) -> Self {
27        Self {
28            id: id.into(),
29            scope: Scope::Singleton,
30            dependencies: Vec::new(),
31            tags: Vec::new(),
32        }
33    }
34
35    /// Sets the service scope.
36    #[must_use]
37    pub const fn with_scope(mut self, scope: Scope) -> Self {
38        self.scope = scope;
39        self
40    }
41
42    /// Declares dependencies resolved before the factory runs.
43    #[must_use]
44    pub fn with_dependencies(mut self, dependencies: Vec<Reference>) -> Self {
45        self.dependencies = dependencies;
46        self
47    }
48
49    /// Adds a service tag (for example `event.subscriber`).
50    #[must_use]
51    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
52        self.tags.push(tag.into());
53        self
54    }
55
56    /// Service id.
57    #[must_use]
58    pub fn id(&self) -> &str {
59        &self.id
60    }
61
62    /// Service scope.
63    #[must_use]
64    pub const fn scope(&self) -> Scope {
65        self.scope
66    }
67
68    /// Declared dependencies.
69    #[must_use]
70    pub fn dependencies(&self) -> &[Reference] {
71        &self.dependencies
72    }
73
74    /// Service tags used by compile passes.
75    #[must_use]
76    pub fn tags(&self) -> &[String] {
77        &self.tags
78    }
79}