Mahdi Nouri
Mahdi Nouri

Reputation: 1389

Passing object to module with new Android injection

I'm using the new Android injection from dagger 2.11, and i have this simple module :

@Module
public class MyModule{

@MyScope
@Provides
SomeClass provideSomeClass(Context context){
    return new SomeClass(context);
}

}

as you can see i need to pass a context to SomeClass constructor. but i don't know how to do this.

without Android injector i can do it like below :

@Module
public class MyModule{

private Context context;

public MyModule(Context context){
    this.context = context;
}

@MyScope
@Provides
Context provideContext(){return context;}

@MyScope
@Provides
SomeClass provideSomeClass(Context context){
    return new SomeClass(context);
}

}

but since i can't access to MyModule with AndroidInjection.inject() i can't pass context to it.

Upvotes: 0

Views: 436

Answers (1)

mertsimsek
mertsimsek

Reputation: 266

If your module is attached to the application as a singleton, you can use Application Context directly. Or you may want to attach your module to your activity/fragment. In that case, you don't have to pass any parameter to your module because dagger is already passed your activity/fragment to your attached module. I want to show you as a simple sample.

Let say you have MainActivity and MainActivityModule. To get your activity context to your MainActivityModule is that calling AndroidInjection.inject(this); in your MainActivity (before super.onCreate()). Here is that module which has context.

@Module
public class MainActivityModule{

public MainActivityModule(MainActivity mainActivity){
    // you can use your main activity as a context.
}

Upvotes: 1

Related Questions