-
Notifications
You must be signed in to change notification settings - Fork 3
05. Auto wiring & dependency resolution
###Auto-wiring. Dependency resolution mechanism.
How does Yadic decide how to create a class instance?
First it tries to instantiate an object using the public constructor with the most parameters. If some of the collaborators are not available because they haven't been injected to the container or cannot be created because of the missing dependencies, Yadic will pick the next constructor with the greatest number of parameters. So basically, it's a shrinking search process for a valid constructor. The last constructor that's examined is a no argument public constructor (it it exists).
If none of the constructors matches then the same approach is used with public static factory methods (excluding static methods that self referencing). Eventually, if the object cannot be created Yadic will throw a ContainerException. Let's take a look at an example:
container.add(ReservationService.class);
container.get(ReservationService.class);
public class ReservationService {
// private constructors are never called by Yadic
private ReservationService() {
....
}
// (2) called when ReservationRepository is in a container, but ClientRepository isn't
public ReservationService(ReservationRespository reservationRepository) {
....
}
// (1) called when ReservationRepository and ClientRepository are in a container
public ReservationService(ReservationRespository reservationRepository, ClientRepository clientRepository) {
....
}
// (3) called when neither ReservationRepository nor ClientRepository are found in a container
public static ReservationService createReservationService() {
....
}
}
In the code above, Yadic will first try to invoke the constructor with two arguments. If it doesn't succeed it will try the constructor with one argument. If it doesn't succeed it will try the static factory method. The private constructor will be ignored.