Domanda

I have a question about using Gin to inject GWT Async RPC service.

I have two classes both using the same Async service:

class TheViewA {    
    @Inject
    public TheViewA(MyServiceAsync myServiceASync) {
        ....
    }
}


class TheViewB {
    @Inject
    public TheViewB(MyServiceASync myServiceASync) {
        ....
    }
}

This works fine. However, I found out this will cause GWT internally call:

GWT.create(MyServiceASync.class) 

twice for each injection. I don't know what is the disadvantage of this, but I am thinking they can both share a single MyServiceAsync instance.

Can someone tell me how to configure Gin (Guice) so that only one instance of MyServiceAsync is created for both injection?

Or Is it OK to create separate instances for both injection and why?

Many thanks.

È stato utile?

Soluzione

When it comes to injection, if Gin does not find a bind for a given type, it automatically fallsback to GWT.create() to create an instance. This is why ClientBundle/GWT-RPC/i18n and the like, simply Just Works, and you do not have to bind them into your own extension of AbstractGinModule.

Of course when Gin finds another injection of the same type, it injects another instance. To create and inject a singleton instance simply bind your GWT-RPC async service interface into @Singleton scope. Like this:

public class YourModule extends AbstractGinModule {
  @Override
  protected void configure() {
    bind(MyServiceAsync.class).in(Singleton.class);
  }
}

Or you can create a Provider<MyServiceAsync> that always returns a singleton instance, but the previous approach is far simpler.

A singleton async instance injected throughout your application, is generally preferred.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top