views:

215

answers:

3

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?

+1  A: 

Solving a performance problem that doesn't exist isn't a good approach. Have you done any profiling to verify the problem?

If not, consider doing that first.

Jörn Zaefferer
This really seem to be turning into a mantra :)
willcodejavaforfood
A: 

I would register B within the session container as well. Any other dependency of B you can leave in the root container. Assume B has another dependency on C. So you can do the following:

// during startup
final MutablePicoContainer root = new PicoBuilder().build();
root.addComponent(C.class, C.class);

// later, initialize sessions
final MutablePicoContainer session = new PicoBuilder(root)
    .implementedBy(TransientPicoContainer.class)
    .build();
session.addComponent(B.class, B.class);
session.addComponent(new A());

// some request
System.out.println(session.getComponent(B.class));
ordnungswidrig
+1  A: 

Did you enable caching on your container (or are you using Pico 1.x)?

Try reading this, maybe disabling the cache is enough to solve this problem.