-
Notifications
You must be signed in to change notification settings - Fork 3
12. Container hierarchies
###Container hierarchies
Many DI containers encourage you to create one big container that stores the entire dependency graph. The same containers provide different scopes where you can put your objects. Yadic goes the other way. It lets you create as many containers as you want without performance penalty. You create the container in a given scope provided by Java and this scope defines the lifecycle of your container. Let's take a look at an example that will make it clear.
Imagine we're writing a web application. This application will have some application scope objects (e.g. jobs scheduler, search engine directory etc.) and some request scope objects (e.g. form parameters). We think that the DI container shouldn't know anything about application scope or a request scope. Those are the responsibilities of a web application. So the sample code could look like that:
public class WebApplication {
private final Container applicationScope = new SimpleContainer();
public Response handle(final Request request) throws Exception {
// createRequestScope() will be called here
}
// method called on each request
private Container createRequestScope() {
final Container requestScope = new SimpleContainer(applicationScope);
...
}
}
As we can see in the code above, we're using Java scoping to crate one container that will store application scope objects and one container that will store request scope objects. Please note how the requestScope object gets a reference to the application scope container. We can create those parent/child structures by passing a reference to a parent container as a parameter to the child container's constructor. If we ask a child container for some object that it doesn't have, it will go to the application scope container and will ask it for the same object.