How to manage dynamic dependencies with PicoContainer?

Say I have two classes A and B, with B depending on A.

public class A {}

public class B {
    public B(A a) {}
}

Easily resolve B in one 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 would like to have different instances Bfor different sessions with variable instances A. I think of something like that.

    // 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));

The code above does not work, because when you request sessionfor, Bit asks for the parent container for it root. Bfound there but allowed only inside rootand his parents, which leads toUnsatisfiableDependenciesException.

Is there a good way to make this work? Or is it an anti-pattern and will I solve the problem wrong?

+3
source share
3

B . B, . , B C. , :

// 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));
0

, , . - , ?

, .

+1

( Pico 1.x)?

this, , .

+1

Source: https://habr.com/ru/post/1708174/


All Articles