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)
}
You don't need to use provider here. Provider is useful to resolve cyclic dependency references.
In your case, you can simply do:
And then direct inject
ArtworkServicein your controller:Provider would have come into the picture, if you had a cycle reference. For example:
Here, we have cycle
ArtworkService->StatusChange&&StatusChange->ArtworkServiceSo, provider comes in rescue in these situations. You can resolve this by: