- Dependency Injection
- Dependency Injection Containers
- Dependency Injection Benefits
- When to use Dependency Injection
- Is Dependency Injection Replacing the Factory Patterns?
- The Opportunities Missed by Annotation Based Dependency Injection
- Design of a Dependency Injection (DI) Container
- Butterfly Container Script - Design Considerations
- Butterfly DI Container - Internal Design
- Butterfly DI Container - Global and Local Factories
Butterfly DI Container - Global and Local Factories
In Butterfly Container there is a difference between local and global factories. As you saw earlier, a factory definition (AKA factory chain) is often translated into a chain of factories. Normally, a factory definition is broken into factories like this:
- One global factory, which can be referenced from other global factories
(other factory definitions).
- A chain of local factories which can only be referenced by factories within the same global factory defintion the local factories are part of.
Here is an example factory definition:
global1 = * com.jenkov.MyObject().getName();
And here is how the factory chain/graph looks inside the container (GF = Global Factory, LF = Local Factory):
If a global factory references another global factory, these two global factories are linked too, inside the container. Here is a configuration example and the corresponding factory graph:
global1 = * com.jenkov.MyObject(); global2 = * global1.getName();
When an instance is obtained from a factory, the factory's
is called. This is what you see happening in the factory graph for
Replaceable Global Factories
One of the design goals for Butterfly Container was to enable runtime replacement of factories. This is not so easy, however, when all the factories are linked together inside the cotainer.
To solve this problem a factory proxy was introduced which encapsulates the global factories. That way the concete global factory inside the global factory proxy can be replaced at runtime. Therefore, the object graph from the previous section really looks like this:
As you can see, the local factory calling the
global1 factory is really
global1's factory proxy. If the definition (factory chain)
on the inside of this proxy is replaced with a new, this will have effect for all other
factories linked to it.