-
Notifications
You must be signed in to change notification settings - Fork 3
07. Activators
Jim Riordan edited this page Aug 10, 2016
·
1 revision
###Adding instances with an activator
In some situations injecting objects to a container cannot be accomplished using simple mechanisms described in the earlier sections and we need an activator. To explain the concept of activators let's take a look at the following example.
container.add(DBConfig.class);
container.addActivator(DB.class, DBActivator.class);
public class DBActivator implements Callable {
private final DBConfig config;
public DirectoryActivator(DBConfig config) {
this.config = config;
}
public DB call() throws Exception {
if (isInMemoryDB(config)) {
return new InMemoryDB();
}
return new RealDB(config));
}
...
}
Activator is an implementation of a Callable. Inside a call method we define how our object should be created. In the code above we use an activator to instantiate a correct DB implementation based on the database config object. In case of any exceptions inside the call method, Yadic will raise a ContainerException.
Note: the activator will be called only once, even in a multithreaded environment.