mirror of
https://github.com/mbierlee/poodinis.git
synced 2024-11-15 04:04:01 +01:00
Add single instance scope, make it the default scope of new registrations
This commit is contained in:
parent
0c084a43b9
commit
4f2f0fbe59
|
@ -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;
|
||||||
}
|
}
|
||||||
|
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -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");
|
||||||
|
}
|
||||||
}
|
}
|
Loading…
Reference in a new issue