use crate::container::{Container, Slots};
use crate::sync::ConstructionLock;
use crate::{ResolveError, Resolver};
use std::fmt;
use std::sync::{Arc, OnceLock};
pub struct Scope {
state: ScopeState,
container: Arc<Container>,
}
#[derive(Default)]
pub(crate) struct ScopeState {
slots: OnceLock<Slots>,
pub(crate) construction: ConstructionLock,
}
impl Scope {
pub(crate) fn new(container: Arc<Container>) -> Self {
Self {
state: ScopeState::default(),
container,
}
}
pub fn resolve<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Arc<T>, ResolveError> {
Resolver::scoped(&self.container, &self.state).resolve()
}
pub fn resolve_all<T: ?Sized + Send + Sync + 'static>(
&self,
) -> Result<Vec<Arc<T>>, ResolveError> {
Resolver::scoped(&self.container, &self.state).resolve_all()
}
}
impl fmt::Debug for Scope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Scope").finish_non_exhaustive()
}
}
impl ScopeState {
pub(crate) fn slots(&self, container: &Container) -> &Slots {
self.slots
.get_or_init(|| Slots::new(container.scoped_count))
}
}