How to use injector's getIntance() method to pass additional arguments to constructor

47 views
Skip to first unread message

Xin Yao

unread,
Jun 24, 2014, 3:56:12 PM6/24/14
to google...@googlegroups.com
Hi,
I have a class Command that I want to leverage Guice's injector as follows. Class Backend is a singleton and should be injected by Guice. But I'd like to be able to pass in argument entity at runtime.

public class Command {
  private final Backend backend;

  @Inject
  public Command(Backend backend, @Assisted Entity entity) {
      this.backend = backend.
  }
}

I wonder if I can do the following. I looks with injector.getInstance does not let me specify an argument, i.e. entity, to pass in.

@Singleton
public class CommandFactory {

  private Injector injector;

  public StepCommandFactory() {
    injector = Guice.createInjector(new ApiFeModule()); // ApiFeModule is a module to be used
  }

  public Command createCommand(Entity entity) {
    switch (entity.getOperation()) {
      Command cmd;
      case CREATE_VM:
        cmd = injector.getInstance(VMCreateStepCmd.class);
        break;
      case CREATE_DISK:
        cmd = injector.getInstance(DiskCreateStepCmd.class);
        break;
      case ATTACH_DISK:
        cmd = injector.getInstance(DiskAttachStepCmd.class);
        break;
      default:
        throw new InternalException(String.format("Invalid Operation %s to create command",
            entity.getOperation()));
    }

    return cmd;
  }
}

Xin Yao

unread,
Jun 24, 2014, 3:57:33 PM6/24/14
to google...@googlegroups.com
Correction:

public Command createCommand(Entity entity) {
    Command cmd; // how to I pass in entity variable
    switch (entity.getOperation()) {
      case CREATE_VM:
        cmd = injector.getInstance(
Reply all
Reply to author
Forward
0 new messages