How to inject Injector?

Viewed 23455

Situation: i need lazy dependency instantiation in some FooClass, so i pass Injector to class as a constructor parameter.

private final Injector m_injector;
    
public FooClass(@Named("FooInjector") Injector injector) {
    m_injector = injector;
}

But guice doesn't permit to bind core classes (injectors, modules and etc). What is the solution?

4 Answers

You should not be using the Injector directly. Rather pass in the Provider<FooClass> instead. Also, you should be injecting the provider in the places where you use FooClass.

private final Provider<FooClass> provider;

@Inject
public ClassWhereFooIsUsed(Provider<FooClass> provider) {
    this.provider = provider;
}

.... somewhere else
FooClass f = provider.get(); // This is lazy

As @gpampara said, Provider<T> should be used for lazy/optional initialization. Also, as I said in my answer to your other question, you should be avoiding references to the Injector in your code in almost all cases.

That said, in a class that is created by Guice, the Injector that is creating the object can be injected just by declaring a dependency on Injector. The Injector is automatically available for injection without you declaring any binding for it.

If you do inject the Injector, you should think about WHY you want to do that. Why don't you just declare dependencies on the actual interfaces/classes the class depends on? It's just as easy to add a new dependency to the constructor as it is to retrieve an instance of some dependency through the Injector elsewhere in your code, and it makes the code far more understandable as well.

Related