Difference of Dagger 2 scopes
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)
}
}
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.
@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