Karthik Balasubramanian
Karthik Balasubramanian

Reputation: 1157

Play 2.1 with Guice 3.0 - Access not available outside Controller classes

Am trying to learn how guice plays with Play 2.1 framework. I have a service to which I need access outside the service package. I have placed the below in Global file

 protected Injector configure() {
      injector =  Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(MyService.class).to(MyServiceImpl.class).in(Singleton.class);
            }
        });

        return injector;
    }

    @Override
    public <A> A getControllerInstance(Class<A> clazz) throws Exception {
        return injector.getInstance(clazz);
    }

Inside the controller class am able to get to my object by doing below and everything seems to be fine

@Inject
MyService serviceObj  

But elsewhere outside the controller the same object appears to be null. For example I have a core module which takes care of talking to the service. The controller classes hands out the job to the core module. I need to be able to get hold of this MyService obj in the core module classes.

What am I missing here guys?

Thanks Karthik

Upvotes: 1

Views: 365

Answers (2)

Christopher Hunt
Christopher Hunt

Reputation: 2081

As an alternative to static injection, see the play-guice sample here:

http://typesafe.com/activator/template/play-guice

Guice can be used in a conventional manner with Play.

Upvotes: 0

Karthik Balasubramanian
Karthik Balasubramanian

Reputation: 1157

I had figured a way out to do this.

In my configure method I had to use this

  protected Injector configure() {
      injector =  Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                requestStaticInjection(TheClassThatNeedsMyService.class);
            }
        });

        return injector;
    }

And in my TheClassThatNeedsMyService I had to just do

@Inject MyService serviceObj;

Just for reference this is how my Service class looks like

@ImplementedBy(MyServiceImpl.class)
public interface MyService{
...
}

@Singleton
public class MyServiceImpl implements MyService{
...
}

Now am able to get access to my service object whereever I want in my application. Hope it helps someone

Thanks Karthik

Upvotes: 1

Related Questions