Singleton Dagger2 components

351 views Asked by At

I'm using Dagger2 in a google appengine project and I have several servlets that make use of, what should be, a singleton instance of a given object (MyObject).

@Singleton
@Component(modules = {MyModule.class})
public interface MyComponent {
  IMyObject object();
}

I then need DaggerMyComponent.create() to be a singleton too so that I can get the same IMyObject across all servlets. To do so, I added a

DaggerMyComponent INSTANCE = DaggerMyComponent.create()

to my MyComponent interface. However, that still allows create() to be called again by mistake and it doesn't necessarily look like a pretty solution to me.

Any ideas?

Thanks!

1

There are 1 answers

0
riwnodennyk On

Unfortunately the docs seem to be saying that Dagger doesn't provide such a limitation so far as for version 2.0.1

In order to get the proper behavior associated with a scope annotation, it is the caller's responsibility to instantiate new component instances when appropriate. A Singleton component, for instance, should only be instantiated once per application, while a RequestScoped component should be instantiated once per request.

http://google.github.io/dagger/api/latest/dagger/Component.html