2

Would like to know if its good to mix dependency injection with the factory patterns ? I would create differents kind of object at runtime and use them where DI is good to inject stuff so it is ok to inject in the factory construction such passing connection string or something ?

Thanks.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Rushino
  • 9,415
  • 16
  • 53
  • 93
  • 1
    Here's a list of Q&As that talk about DI and Abstract Factory: http://stackoverflow.com/questions/2280170/why-do-we-need-abstract-factory-design-pattern/2280289#2280289 – Mark Seemann Feb 05 '11 at 18:20

2 Answers2

5

It's quite common actually. If you need instances of a certain class on demand, you'll inject a factory instead of a specific object. You should be using the container to construct those objects however (if it needs other objects to be constructed), to stay in the pattern and don't create dependencies.

Femaref
  • 60,705
  • 7
  • 138
  • 176
1

Absolutely! You can even inject objects into your factories!

public class UserFactory
  private final UserStore userStore;

  @Inject
  UserFactory(UserStore userStore) {
    this.userStore;
  }

  // etc
}

public class CreateUserAction implements Action {
  private final UserFactory userFactory;

  @Inject
  CreateUserAction(UserFactory userFactory) {
    this.userFactory = userFactory;
  }

  @Override
  void performAction() {
    User user = userFactory.newUser().withRandomId().persisted().build();
  }
}
NamshubWriter
  • 23,549
  • 2
  • 41
  • 59