Use instantiation context to decide whether to autowire or not

This commit is contained in:
Mike Bierlee 2015-01-25 19:46:17 +01:00
parent 9d931f511b
commit 5ebb5805cf
3 changed files with 29 additions and 16 deletions

View file

@ -92,9 +92,20 @@ class AutowiredRegistration(RegistrationType : Object) : Registration {
super(registeredType, typeid(RegistrationType));
}
public override Object getInstance() {
RegistrationType instance = cast(RegistrationType) super.getInstance();
container.autowire(instance);
public override Object getInstance(InstantiationContext context = new AutowireInstantiationContext()) {
RegistrationType instance = cast(RegistrationType) super.getInstance(context);
AutowireInstantiationContext autowireContext = cast(AutowireInstantiationContext) context;
enforce(!(autowireContext is null), "Given instantiation context type could not be cast to an AutowireInstantiationContext. If you relied on using the default assigned context: make sure you're calling getInstance() on an instance of type AutowiredRegistration!");
if (autowireContext.autowireInstance) {
container.autowire(instance);
}
return instance;
}
}
class AutowireInstantiationContext : InstantiationContext {
public bool autowireInstance = true;
}

View file

@ -22,7 +22,7 @@ class Registration {
this.instantiatableType = instantiatableType;
}
public Object getInstance() {
public Object getInstance(InstantiationContext context = new InstantiationContext()) {
if (registationScope is null) {
throw new NoScopeDefinedException(registeredType);
}
@ -130,3 +130,5 @@ public string toConcreteTypeListString(Registration[] registrations) {
}
return concreteTypeListString;
}
class InstantiationContext {}

View file

@ -179,7 +179,7 @@ version(unittest) {
container.register!ComponentA;
auto registration = new AutowiredRegistration!ComponentB(typeid(ComponentB), container).singleInstance();
auto instance = cast(ComponentB) registration.getInstance();
auto instance = cast(ComponentB) registration.getInstance(new AutowireInstantiationContext());
assert(!instance.componentIsNull());
}