Picocontainer: Inject multiple objects of same type

332 views Asked by At

I am using DI and have the following

  public DoSomethingWithUsers(User user1, User user2){
      this.user1 = user1;
      this.user2 = user2;
  }

Notice that the same type is being injected twice.

As I proceed with my coding/testing I noticed that all methods being run on user1 and user2 are effecting user1.

Is there a way to inject multiple objects of the same type with picocontainer and have them be "independent" objects as intended ? Or, is there a different DI package that would allow for such behavior ?

thnx

1

There are 1 answers

0
xeye On

You have the following options with pico:

1) You can inject the collection or array of users like DoSomethingWithUsers(User[] users) and it will be populated with all User instances available in the container but the order is not guaranteed, it's convenient if you were going to perform group operation anyway.

2) Hint component key with ComponentParameter

MutablePicoContainer pico = new DefaultPicoContainer();
pico.addComponent("user1", userInstance1);
pico.addComponent("user2", userInstance2);
pico.addComponent(DoSomethingWithUsers.class, DoSomethingWithUsers.class, 
    new Parameter[]{ new ComponentParameter("user1"), new ComponentParameter("user2")}); 

3) You can leverage parameter names like in this example: http://picocontainer.com/parameter-names.html

More examples here: http://picocontainer.com/arrays-collections-and-maps.html