Hi, I'm writting a "small" tutorial for my fellows, and I feel that this part was worth sharing with you, to get feedback and discussion on it. Thanks.
Dealing with multiplicity in DI. Multiplicity is always a pain. Unless you have a Singleton (manytoOne) , or oneToOne, all the other cases are complicated. OneToOne is the default multiplicity for guice. Singleton is easily configured in a module. Though, complicated case are very frequent. Some are design flaw, but you can't expect every design to be perfect, and some are not. For instance, I have "several" ErrorManager"s in my "eclipse-like" application, one for each type of editors, and one for general purpose. How to I get the right ErrorManager ? I'll list all the way I know to deal with it. Not all behave the same, all have pro and cons. 1/ without Guice Design a singleton service that handles a collection of ErrorManager, and then dispatch errors to the appropriate sub ErrorManager. You'll have to redesign the ErrorManager, so it can take as parameter the type of Editor, and redispatch to the appropriate ErrorManager. In Guice, you have converted a ManytoMany multiplicity into a Singleton, and handle the multiplicity by "hand". 2/ With annotated bindings You can create an ErrorScope Annotation, that has the Editor Type as parameter. Then in you injectee, you'll do: @Inject ErrorScope( XMLEditor.TYPE) ErrorManager manager; An in your Module: bind(ErrorManager.class).annotatedWith(ErrorScope(XMLEditor.TYPE) ).to ( XMLErrorManager.class); 3/ With private modules You can inject each Editor within it's own private Module. That means it will have access to every bindings, plus the one you defined at module level. Then in you injectee will look like @Inject ErrorManager manager; In your main Injector (or in the parent module) : Injector i = Guice.createInjector( new XMLEditorModule(), new JavaEditorModule() , ...) Where XMLEditorModule extends PrivateModule instead of abstractModule, and is configured as follow bind(ErrorManager.class).to(XMLErrorManager.class); Is there other ways to handle this example of multiplicity ? Which one is the best for you ? For me, 1/ is an escape line 2/ forces you to change the interface ErrorManager and change all the code that was using the previous interface. 3/ is the best one, but increases the complexity of configuring your modules. -- You received this message because you are subscribed to the Google Groups "google-guice" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.
