How to use provider for dependency injection using guice in playframework

987 views Asked by At

I am using playframework 2.4 here is my code

trait UserRepositoryTrait {
  val userRepo:UserRepository
  val sessionRepo:SessionRepository 
}

class UserRepositoryImpl extends UserRepositoryTrait {
  @Inject @Named("userRepo")val userRepo:UserRepository= null 
  @Inject @Named("sessionRepo") val sessionRepo:SessionRepository = null
  }

and here is module class

class UserDependencyModule extends AbstractModule { 

    @Override
      protected def configure() {
        bind(classOf[UserRepository]).annotatedWith(Names.named("userRepo")).toInstance(new UserRepo)
        bind(classOf[SessionRepository]).annotatedWith(Names.named("sessionRepo")).toInstance(new SessionRepo)
                bind(classOf[UserRepositoryTrait]).to(classOf[UserRepositoryImpl])
      }

}

in application.conf

play.modules.enabled += "models.guice.UserDependencyModule"

everything works fine if I inject this trait in a controller but i want to inject this trait into a class here is the code

class StatusChange @Inject() (userRepository:UserRepositoryTrait) {
}

and i need to callStatusChange.scala in Service.scala class how can i instantiate StatusChange.scala object

class ArtworkService() {

val status= new StatusChange(//what should i add here?)

}

i did read on providers but I am unable to understand how can I use it for my scenario ?please guide me

update if i do it like this will be correct ?

class ArtworkService @inject (userRepository: UserRepositoryTrait) {

    val status= new StatusChange(userRepository)

    }

and in the controller

class MyController @inject (userRepository: UserRepositoryTrait)
{
 val artworkService = new ArtworkService(userRepository)
}
1

There are 1 answers

0
Tarang Bhalodia On

You don't need to use provider here. Provider is useful to resolve cyclic dependency references.

In your case, you can simply do:

class ArtworkService @Inject (status: StatusChange) {}

And then direct inject ArtworkService in your controller:

class MyController @Inject (artworkService: ArtworkService) {}

Provider would have come into the picture, if you had a cycle reference. For example:

class ArtworkService @Inject (status: StatusChange) {}

class StatusChange @Inject (artworkService: ArtworkService) {}

Here, we have cycle ArtworkService -> StatusChange && StatusChange -> ArtworkService So, provider comes in rescue in these situations. You can resolve this by:

class ArtworkService @Inject (status: StatusChange) {}

class StatusChange @Inject (artworkServiceProvider: Provider[ArtworkService]) {}