Android – Simplest way to create a Singleton w/ Dagger 2

androiddagger-2singleton

Do I need to setup Modules, Providers and Interfaces (Components)?
Seems like quite a bit of overhead just to be able to inject a singleton.

Can someone provide a simple singleton example using Dagger 2? (also show how one can set properties of the singleton like the context so you don't need to pass it in every time you use the singleton)

Best Answer

You only need modules for things that you can't annotate with @Inject constructor (because for example, the framework creates it for you - like context). If you can't add an @Inject constructor, you also need to specify a void inject(...) method in the component as well.

However, if you can create it with a @Inject constructor, then @Inject works as a field annotation as well

@Component(modules={ContextModule.class})
@Singleton
public interface SingletonComponent {
    void inject(MainActivity mainActivity);
}

@Module
public class ContextModule {
    Context context;

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

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

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


@Singleton
public class MySingleton {
    @Inject Context context;
    @Inject MyOtherSingleton myOtherSingleton;

    @Inject
    public MySingleton() {
    }
}

You can also do constructor parameters

private final Context context;
private final MyOtherSingleton myOtherSingleton;

@Inject
public MySingleton(Context context, MyOtherSingleton myOtherSingleton) {
    this.context = context;
    this.myOtherSingleton = myOtherSingleton;
}

SingletonComponent singletonComponent = DaggerSingletonComponent.builder()
           .contextModule(CustomApplication.this)
           .build();

// and elsewhere

@Inject
MySingleton mySingleton;

// ...
    singletonComponent.inject(this);

Verified to work:

08-23 04:39:28.418 com.zhuinden.rxrealm D/DogView: My singleton has [com.zhuinden.rxrealm.application.CustomApplication@53348a58] and [com.zhuinden.rxrealm.application.injection.test.MyOtherSingleton@5336bb74]
08-23 04:39:36.422 com.zhuinden.rxrealm D/CatView: My singleton has [com.zhuinden.rxrealm.application.CustomApplication@53348a58] and [com.zhuinden.rxrealm.application.injection.test.MyOtherSingleton@5336bb74]