nani
nani

Reputation: 382

dagger2 constructor injection how to provide dependency without module

I've read that constructor injections don't require a module. So I have this questions.

  1. If I have this constructor injection:

    private Model realmModel;
    
    @Inject
    public MainActivityPresenter(Model realmModel) {
        this.realmModel = realmModel;
    }
    

and this component:

@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {


    Model realmModel();
    void inject(MainActivity activity);


}

if in my MainActivity I do it:

((MyApp)getApplication()).createAppComponent().inject(this);

how could I pass the realmModel parameter to the presenter constructor injection?

EDIT: this is the model:

 Presenter presenter;

 @Inject
 public RealmModel(Presenter presenter) {
    this.presenter = presenter;

}

Thanks

Upvotes: 0

Views: 946

Answers (2)

Jileshl
Jileshl

Reputation: 161

Three ways to solve this problem

1) Give a module which does the provide of the Relam Model

 @Provides
 @Singleton
 public Model providesRealmModel() {
     return new Model();
 }

2) Make your RelamModel class also constructor injected

class Model {
   @Inject
   public Model() {}
} 

The Trick in construction injection is all its dependencies should also be constuctor injeceted then it would work fine. (From experience your model would need application context. look at the 3 option for ways to implement external Dependencies

3) Provide Model as external dependency.

 @Module
 public class ModelModule {
    private Model relamModel;
    public ModelModule(Model relamModel) {
       this.relamModel = relamModel
    }
 }

@Component(module={ModelModule.class}) 
public interface ApplicationComponent {
}

Take a look at the series of videos from twisted eqautions these were my first video tutorial on dagger2. I found it really helpful. Hope it helps you too https://www.youtube.com/watch?v=Qwk7ESmaCq0

Upvotes: 1

Matias Elorriaga
Matias Elorriaga

Reputation: 9150

You have two choices:

  1. use a module with a provide method
  2. annotate the constructor of Model with @Inject, doing that when you pass realmModel in the presenter contructor, the model constructor will be called.

I prefer to use modules, but that's just my opinion.

Upvotes: 0

Related Questions