Add single instance scope, make it the default scope of new registrations

This commit is contained in:
Mike Bierlee 2014-05-20 22:03:50 +02:00
parent 0c084a43b9
commit 4f2f0fbe59
3 changed files with 29 additions and 2 deletions

View file

@ -44,7 +44,7 @@ class Container {
checkValidity!(InterfaceType)(registeredType, instantiatableType); checkValidity!(InterfaceType)(registeredType, instantiatableType);
} }
Registration newRegistration = { registeredType, instantiatableType, new NullScope() }; Registration newRegistration = { registeredType, instantiatableType, new SingleInstanceScope(instantiatableType) };
registrations[newRegistration.registeredType] = newRegistration; registrations[newRegistration.registeredType] = newRegistration;
return newRegistration; return newRegistration;
} }

View file

@ -10,7 +10,7 @@ struct Registration {
throw new NoScopeDefinedException(registeredType); throw new NoScopeDefinedException(registeredType);
} }
return instantiatableType.create(); return registationScope.getInstance();
} }
} }
@ -29,3 +29,20 @@ class NullScope : RegistrationScope {
return null; return null;
} }
} }
class SingleInstanceScope : RegistrationScope {
TypeInfo_Class instantiatableType = null;
Object instance = null;
this(TypeInfo_Class instantiatableType) {
this.instantiatableType = instantiatableType;
}
public Object getInstance() {
if (instance is null) {
instance = instantiatableType.create();
}
return instance;
}
}

View file

@ -12,4 +12,14 @@ version(unittest) {
registration.registeredType = typeid(TestType); registration.registeredType = typeid(TestType);
assertThrown!(NoScopeDefinedException)(registration.getInstance()); assertThrown!(NoScopeDefinedException)(registration.getInstance());
} }
// Test getting instance from single instance scope
unittest {
Registration registration = Registration();
registration.registeredType = typeid(TestType);
registration.registationScope = new SingleInstanceScope(typeid(TestType));
auto instance1 = registration.getInstance();
auto instance2 = registration.getInstance();
assert(instance1 is instance2, "Registration with single instance scope did not return the same instance");
}
} }