square / dagger

A fast dependency injector for Android and Java.
https://square.github.io/dagger/
Apache License 2.0
7.31k stars 3.06k forks source link

Is it OK to create an instance of a dependency already in the module constructor #535

Closed tercanfurkan closed 8 years ago

tercanfurkan commented 8 years ago

Using dagger 1.2.2

There is a case that I need to construct my dependency before it is provided to the classes injecting it. Is it possible to create an instance of this dependency already in the module's constuctor? This dependency is a scoped dependency, so I am worried if doing the following will lead to a leakage.

HERE IS WHAT I WANT TO DO:

@Module(
        injects = { Controller.class},
        complete = false,
        addsTo = InitModule.class
)
public class SubModule {

    public ScopedDependency dep;

    public SubModule() {
        this.dep = new ScopedDependency();
    }

    @Provides
    @Singleton
    public ScopedDependency provideScopedDependency() {
        return dep;
    }
}

INSTEAD OF THIS:

@Module(
        injects = { Controller.class },
        complete = false,
        addsTo = InitModule.class
)
public class SubModule {

    @Provides
    @Singleton
    public ScopedDependency provideScopedDependency() {
        return new ScopedDependency();
    }
}

When I decide to release the scopedGraph (scopedGraph = null), will I leak the ScopedDependency instance if I use the first approach?

swankjesse commented 8 years ago

Please use stackoverflow.com for usage questions.