Say I have two classes A and B, with B depending on A.
public class A {}
public class B {
public B(A a) {}
}
It's easy to resolve B in a single PicoContainer.
final MutablePicoContainer root = new PicoBuilder().build();
root.addComponent(new A());
root.addComponent(B.class, B.class);
System.out.println(root.getComponent(B.class));
But I'd like to have different instances of B
for different sessions, with variable instances of A
. I'm thinking about something like this.
// during startup
final MutablePicoContainer root = new PicoBuilder().build();
root.addComponent(B.class, B.class);
// later, initialize sessions
final MutablePicoContainer session = new PicoBuilder(root)
.implementedBy(TransientPicoContainer.class)
.build();
session.addComponent(new A());
// some request
System.out.println(session.getComponent(B.class));
Above code isn't working, because when asking session
for a B
it asks the parent container root
for it. B
is found there, but resolved only within root
and its parents, leading to an UnsatisfiableDependenciesException.
Is there any good way to make this work? Or is this an anti-pattern, and I'm solving the problem in the wrong way?