Add scope setter for single instance scopes

This commit is contained in:
Mike Bierlee 2014-05-20 22:12:14 +02:00
parent 4f2f0fbe59
commit 64e25715cf
3 changed files with 18 additions and 2 deletions

View file

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

View file

@ -46,3 +46,8 @@ class SingleInstanceScope : RegistrationScope {
return instance; return instance;
} }
} }
public Registration singleInstance(ref Registration registration) {
registration.registationScope = new SingleInstanceScope(registration.instantiatableType);
return registration;
}

View file

@ -16,10 +16,20 @@ version(unittest) {
// Test getting instance from single instance scope // Test getting instance from single instance scope
unittest { unittest {
Registration registration = Registration(); Registration registration = Registration();
registration.registeredType = typeid(TestType);
registration.registationScope = new SingleInstanceScope(typeid(TestType)); registration.registationScope = new SingleInstanceScope(typeid(TestType));
auto instance1 = registration.getInstance(); auto instance1 = registration.getInstance();
auto instance2 = registration.getInstance(); auto instance2 = registration.getInstance();
assert(instance1 is instance2, "Registration with single instance scope did not return the same instance"); assert(instance1 is instance2, "Registration with single instance scope did not return the same instance");
} }
// Test set single instance scope using scope setter
unittest {
Registration registration = Registration();
registration.instantiatableType = typeid(TestType);
auto chainedRegistration = registration.singleInstance();
auto instance1 = registration.getInstance();
auto instance2 = registration.getInstance();
assert(instance1 is instance2, "Registration with single instance scope did not return the same instance");
assert(registration is chainedRegistration, "Registration returned by scope setting is not the same as the registration being set");
}
} }