Add existing instance registration scope

This commit is contained in:
Mike Bierlee 2014-05-21 00:26:44 +02:00
parent bb0a8d5746
commit cbecebf43f
3 changed files with 27 additions and 3 deletions

View file

@ -85,3 +85,8 @@ class ExistingInstanceScope : RegistrationScope {
return instance;
}
}
public Registration existingInstance(Registration registration, Object instance) {
registration.registationScope = new ExistingInstanceScope(instance);
return registration;
}

View file

@ -100,7 +100,7 @@ version(unittest) {
container.register!(TestClass)().singleInstance();
auto instance1 = container.resolve!(TestClass);
auto instance2 = container.resolve!(TestClass);
assert(instance1 is instance2);
assert(instance1 is instance2, "Resolved instance from single instance scope is not the each time it is resolved");
}
// Test resolve new instance for type
@ -109,7 +109,16 @@ version(unittest) {
container.register!(TestClass)().newInstance();
auto instance1 = container.resolve!(TestClass);
auto instance2 = container.resolve!(TestClass);
assert(instance1 !is instance2);
assert(instance1 !is instance2, "Resolved instance from new instance scope is the same each time it is resolved");
}
// Test resolve existing instance for type
unittest {
auto container = new Container();
auto expectedInstance = new TestClass();
container.register!(TestClass)().existingInstance(expectedInstance);
auto actualInstance = container.resolve!(TestClass);
assert(expectedInstance is actualInstance, "Resolved instance from existing instance scope is not the same as the registered instance");
}
}

View file

@ -49,7 +49,7 @@ version(unittest) {
auto instance2 = registration.getInstance();
assert(instance1 !is instance2, "Registration with new instance scope did not return a different instance");
assert(registration is chainedRegistration, "Registration returned by scope setting is not the same as the registration being set");
}
}
// Test getting instance from existing instance scope
unittest {
@ -60,4 +60,14 @@ version(unittest) {
assert(expectedInstance is actualInstance, "Registration with existing instance did not return given instance");
}
// Test set existing instance scope using scope setter
unittest {
Registration registration = new Registration(null, null);
auto expectedInstance = new TestType();
auto chainedRegistration = registration.existingInstance(expectedInstance);
auto actualInstance = registration.getInstance();
assert(expectedInstance is expectedInstance, "Registration with existing 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");
}
}