Add removing of registrations

This commit is contained in:
Mike Bierlee 2014-05-31 23:22:29 +02:00
parent 60b1149aea
commit b78e05455d
2 changed files with 19 additions and 7 deletions

View file

@ -59,22 +59,26 @@ class Container {
} }
} }
public ClassType resolve(ClassType)() { public RegistrationType resolve(RegistrationType)() {
TypeInfo resolveType = typeid(ClassType); TypeInfo resolveType = typeid(RegistrationType);
Registration* registration = resolveType in registrations; Registration* registration = resolveType in registrations;
if (!registration) { if (!registration) {
throw new ResolveException("Type not registered.", resolveType); throw new ResolveException("Type not registered.", resolveType);
} }
ClassType instance = cast(ClassType) registration.getInstance(); RegistrationType instance = cast(RegistrationType) registration.getInstance();
this.autowire!(ClassType)(instance); this.autowire!(RegistrationType)(instance);
return instance; return instance;
} }
public void clearRegistrations() { public void clearAllRegistrations() {
registrations.clear(); registrations.clear();
} }
public void removeRegistration(RegistrationType)() {
registrations.remove(typeid(RegistrationType));
}
public static Container getInstance() { public static Container getInstance() {
if (instance is null) { if (instance is null) {
instance = new Container(); instance = new Container();

View file

@ -90,7 +90,7 @@ version(unittest) {
unittest { unittest {
auto container = new Container(); auto container = new Container();
container.register!(TestClass)(); container.register!(TestClass)();
container.clearRegistrations(); container.clearAllRegistrations();
assertThrown!ResolveException(container.resolve!(TestClass)(), "Resolving cleared type does not fail"); assertThrown!ResolveException(container.resolve!(TestClass)(), "Resolving cleared type does not fail");
} }
@ -158,4 +158,12 @@ version(unittest) {
auto cat = container.resolve!ComponentCat; auto cat = container.resolve!ComponentCat;
assert(mouse.cat is cat && cat.mouse is mouse, "Circular dependencies should be autowirable"); assert(mouse.cat is cat && cat.mouse is mouse, "Circular dependencies should be autowirable");
} }
// Test remove registration
unittest {
auto container = new Container();
container.register!TestClass;
container.removeRegistration!TestClass;
assertThrown!ResolveException(container.resolve!TestClass);
}
} }