juminoz
juminoz

Reputation: 3218

Making Guice Injector Singleton for Consistency

I was wondering how the injector is typically used. I understand that it's used mainly at start-up time, but how would you use it at run-time to create an object of certain implementation?

For example, I have an interface User with implementation of UserA, UserB and UserC. My idea of using Guice at run-time is to wrap it in a Singleton class so that I can get retrieve it rather than creating a new injector every time I want to create an instance of User object.

//Create in singleton wrapper class
Injector injector = Guice.createInjector(new SecurityModule());

//Retrieve and use at run-time (Manager is the singleton wrapper class)
Injector injector = Manager.getInstance().getInjector();
User user = injector.getInstance(User.class);

Is this how it's typically done? Basically, I want to make sure that I centralize all configuration so that there is less error (e.g. using the wrong module). It's also easier to manage so if I decided to use a different configuration module, I can just change it in a class, rather than in every Java class that is using it.

Thanks, Jack

Upvotes: 1

Views: 1003

Answers (2)

Fredrik Wendt
Fredrik Wendt

Reputation: 1138

I would write:

public class Manager {
    private static Manager instance;
    // getInstance singleton method left out for brevity
    private Injector injector;
    private Manager() {
        injector = Guice.createInjector(...);
    }
    public <T> T get(Class<? extends T> cls) {
        return injector.getInstance(cls);
    }
}

so you can do

Manager.getInstance().get(User.class) and not have to use the Injector from Guice, allowing you to change Dependency Injection framework without changing your application code.

Upvotes: 1

ColinD
ColinD

Reputation: 110054

You shouldn't need to use the Injector directly in an application except in rare and specific circumstances, and even then you definitely should not make it a static Singleton. If you want to be able to retrieve new instances of User using Guice somewhere in your application, you should just inject a Provider<User> and call get() on it when you need.

Upvotes: 2

Related Questions