Android-CleanArchitecture icon indicating copy to clipboard operation
Android-CleanArchitecture copied to clipboard

Difference of Dagger 2 scopes

Open nikiJava opened this issue 8 years ago • 2 comments

I use Dagger 2 to perform Dependency Inversion rule in my app. I was just looking on Clean Architecture example by Fernando Cejas and I had a question - what is difference between the two approaches presented below:

If I mark the class like so:

@Singleton // or @PerActivity or @PerFragment, nevermind
public class UserDataStoreFactory {

  private final Context context;
  private final UserCache 
}

Or if I create a module, where I define a provide-method and add this module into the any component (PerActivity, PerFragment and so on, nevermind)

@Module
public class SomeModule {
     @Provides
     @Singleton  // or @PerActivity or @PerFragment, nevermind
     UserDataStoreFactory providesUserDataStoreFactory (Context context, UserCache userCache) {
          return new UserDataStoreFactory(context, userCache)
     }
}

nikiJava avatar Feb 14 '17 16:02 nikiJava

The first case, you're marking it purely for readability. The second case you're telling dagger that this provide method can only be used to provide for components with the same scope.

logicError avatar Feb 27 '17 20:02 logicError

@Singleton // or @PerActivity or @PerFragment, nevermind
public class UserDataStoreFactory {

This is used by @Inject annotated constructor

Technically if you don't need to bind the implementation to an interface using a module, then you can skip the new in the module entirely, because Dagger knows how to instantiate things that have a @Inject annotated constructor

Zhuinden avatar Mar 05 '17 17:03 Zhuinden