Skip to content

Commit

Permalink
Make singleton constructor private
Browse files Browse the repository at this point in the history
  • Loading branch information
dmweis committed Nov 23, 2023
1 parent caac468 commit df274ea
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/ioc_container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@ pub enum IocContainerError {

type Handle = Arc<dyn Any + Send + Sync>;

#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone)]
pub struct IocContainer {
map: Arc<Mutex<HashMap<TypeId, Handle>>>,
}

impl IocContainer {
fn new() -> Self {
Self {
map: Arc::new(Mutex::new(HashMap::new())),
}
}

pub fn register<T: Any + Send + Sync>(&self, object: T) {
let type_id = object.type_id();
self.map.lock().unwrap().insert(type_id, Arc::new(object));
Expand Down Expand Up @@ -51,7 +57,7 @@ impl IocContainer {

pub fn global_instance() -> &'static IocContainer {
static INSTANCE: OnceCell<IocContainer> = OnceCell::new();
INSTANCE.get_or_init(IocContainer::default)
INSTANCE.get_or_init(IocContainer::new)
}
}

Expand All @@ -63,15 +69,15 @@ mod tests {

#[test]
fn simple_ioc() {
let container = IocContainer::default();
let container = IocContainer::new();
container.register(A);
let a = container.get::<A>();
assert!(a.is_some());
}

#[test]
fn fail_on_unregistered_type() {
let container = IocContainer::default();
let container = IocContainer::new();
let not_a = container.get::<A>();
assert!(not_a.is_none())
}
Expand Down

0 comments on commit df274ea

Please sign in to comment.