views:

381

answers:

2

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  A: 

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
gpampara
Thx! I'll try it for lazy initialization. But is there really no way to inject Injector?
Alex M
You can get the injector with `@Inject Injector injector`, can be on the constructor / field / method.
gpampara
Did you try this? How configure module? Guice restricts binding to core classes: "Binding to core guice framework type is not allowed: Injector."
Alex M
`@Inject Injector injector` code injects the same `Injector` that used to create instance. So, i suppose, that there is no way to inject other `Injector`.
Alex M
@AlexM: Have a look at `childInjectors` if you really need. In general they should not be needed and you should only use a single injector. There are exceptions but they are rare.
gpampara
Why do you need multiple Injectors? I really can't imagine.
ColinD
+1  A: 

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.

ColinD