scala - @Inject object null: Play dependency injection -
i instantiated using dependency injection in controller class. when try use object using @inject annotation elsewhere, null value. here code skeleton.
@singleton class serviceclient(ws: wsclient, config: configuration) { def response() {...} } class app @inject()(client: serviceclient) extends controller { def getitems = action { obj() } } case class obj() { @inject var client: serviceclient = _ def dostuff() { client.getresponse() //client null null pointer exception. .... } }
the @inject in obj never seems working. , client object null. (i not want pass client param obj.) expectation serviceclient object created in controller should have been injected in obj(). did wrong?
update
injecting obj controller, not option. (in app obj instantiated @ run time complicated rule, using reflection).also dont want have constructor injection in obj. i looking field injection of serviceclient outside of controller.
update2
i able solve problem using
var client: serviceclient = play.api.play.current.injector.instanceof(classof[serviceclient])
in obj class. however, play.api.play.current deprecated in play 2.5 still kind of stuck warning.
you cannot inject dependency class instance without asking di framework. in code manually instantiate obj
means dependency injection magic not happening. in order inject dependency obj
class instantiation should handled di framework. can here is:
inject
serviceclient
eitherobj
constructor or filed:class obj @inject() (client: serviceclient) { // }
it makes sense use simple class instead of case class because case class sounds more "data" class immutable data inside rather service or helper class. actually, current definition of
obj
class should work.inject
obj
, (or, depending on needs)serviceclient
app class:class app @inject()(obj: obj, client: serviceclient) extends controller { def getitems = action { obj.dostuff() } }
i'd recommend read more dependency injection , guice framework used in play default. guice wiki