简体   繁体   中英

Dagger 2 Singleton vs Real Singleton

I am trying to use dagger 2 in my project. Dagger provides a nice way to create singletons and I have a few in my project but Dagger creates a new object graph with every new container for each @Singleton object so we have to create the component in the application level therefor we should provide the application to the class using the singleton and this is not looking really good :(. The question is: Should I keep my old singletons? or should I use dagger?

Dagger is a much better way to manage singletons, in part because you don't need to worry about how to substitute those singletons during unit tests: Your singletons will be injected through means that you can control and override in unit tests (ie constructor arguments and accessible fields).

Dagger creates a new object graph with every new container for each @Singleton object so we have to create the component in the application level

If you want application-level singletons, you will want to keep the same component instance across your application's lifecycle, rather than creating a new one with every new "container". The component will contain and provide the singletons, so you shouldn't ever need more than one object graph active in your application. If some external creator (eg Android or a servlet engine) creates objects on its own outside of Dagger, this may mean you'll need to save your Dagger component in a singleton holder (perhaps a thread-safe public static field) the way you did for your old singletons; this should still be easier to understand and maintain, as you can provide as many singletons as you'd like through Dagger, and only worry about one externally-managed singleton for the component itself.

As an alternative, you could keep your old singletons exactly as you have them, and write @Provides methods in a Module to retrieve those singleton instances when your Dagger-created objects request them. This would allow you to create a new object graph whenever and wherever you'd like, and your singletons will still behave as singletons. I'd caution against this, though, because at that point your singletons will be accessible two different ways in your application, and only the ones that are Dagger-created or Dagger-managed will be easily overridden in tests; this can be confusing and hard to manage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM