Чечил Крым
Чечил Крым

Reputation: 309

About Dagger 2. Connection of @inject and @provide

If there is @inject, then it means there must be @provide? inject field gets its value from @provide method of module?

Upvotes: 1

Views: 491

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81549

Yes if you use Module

@Module
public class SomeModule {
    @Provides
    Unscoped unscoped() {
        return new Unscoped();
    }

    @Provides
    @Singleton
    Scoped scoped() {
        return Scoped();
    }
}

BUT classes with @Inject constructor get automatically appended to your scoped component even if no module is specified for it:

@Singleton
public class Scoped {
    @Inject
    public Scoped() {
    }
}

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

Upvotes: 3

shekar
shekar

Reputation: 1271

If there is @Inject annotation then it's dependency can be provided in two ways :

By Using Provides annotation in module

@Provides
    TasksPresenter provide TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
        return new TasksPresenter(tasksRepository,tasksView);
}

By Using Constructor Injection

 @Inject
    TasksPresenter(TasksRepository tasksRepository, TasksContract.View tasksView) {
        mTasksRepository = tasksRepository;
        mTasksView = tasksView;
    }

One thing to observe here is Constructor Injection solve two thing

  • Instantiate object
  • Provides the object by adding it to Object graph.

Upvotes: 1

Related Questions