-
Notifications
You must be signed in to change notification settings - Fork 3
04. Interface injection
###Adding objects to a container using interfaces
In the previous section we already saw the most basic way of adding objects to a container by calling
container.add(MyClass.class)
In practice, our object's collaborators are not only concrete classes. In a well designed system we usually have interfaces and different implementations of the interfaces are used for production and testing. Let's take a look at the following example.
public class ReservationService {
private ReservationRepository repository;
public ReservationService(ReservationRepository repository) {
this.repository = repository;
}
public Confirmation reserve(Room room) {
// some logic using our repository
}
}
A reservation service is using a ReservationRepository as a collaborator. ReservationRepository is an interface.
public interface ReservationRepository {
public Confirmation reserve(Room room);
}
A reservation repository has two implementations: database-based and in-memory.
public interface DBReservationRepository implements ReservationRepository {
public Confirmation reserve(Room room) { // goes to a database }
}
public interface InMemoryReservationRepository implements ReservationsRepository {
public Confirmation reserv(Room room) { // saves reservations in memory }
}
In our production code we'd like to use a database-based implementation.
Container container = new SimpleContainer();
container.add(ReservationService.class);
container.add(ReservationRepository.class, DBReservationRepository.class);
But in tests we'd like to use an in-memory representation.
Container container = new SimpleContainer();
container.add(ReservationService.class);
container.add(ReservationRepository.class, InMemoryReservationRepository.class);
As you can see, in Yadic you can add objects to the container using an interface name. Actually, you can think of Yadic as a map with class/interface name keys and values being objects of a given type. To retrieve the object back form a container, you have to use an interface name, not a concrete class.
ReservationRepository repository = container.get(ReservationRepository.class);