Prevent endless recursion on autowiring circular dependencies

This commit is contained in:
Mike Bierlee 2014-06-01 23:49:12 +02:00
parent b0df553ca9
commit a53080c109
2 changed files with 17 additions and 3 deletions

View file

@ -31,6 +31,8 @@ class Container {
private Registration[TypeInfo] registrations;
private Registration* registrationBeingResolved;
public Registration register(ConcreteType)() {
return register!(ConcreteType, ConcreteType)();
}
@ -52,8 +54,20 @@ class Container {
throw new ResolveException("Type not registered.", resolveType);
}
auto initialResolve = false;
if (registrationBeingResolved is null) {
registrationBeingResolved = registration;
initialResolve = true;
}
RegistrationType instance = cast(RegistrationType) registration.getInstance();
this.autowire!(RegistrationType)(instance);
if (initialResolve || registrationBeingResolved !is registration) {
this.autowire!(RegistrationType)(instance);
}
if (initialResolve) {
registrationBeingResolved = null;
}
return instance;
}

View file

@ -40,7 +40,7 @@ version(unittest) {
class ComponentMouse {
@Autowire
public ComponentMouse cat;
public ComponentCat cat;
}
// Test register concrete type
@ -133,7 +133,7 @@ version(unittest) {
container.register!ComponentCat;
auto mouse = container.resolve!ComponentMouse;
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 && mouse !is cat, "Circular dependencies should be autowirable");
}
// Test remove registration