[2.4-scala] dependency injection and Scala singleton object

193 views
Skip to first unread message

pishen tsai

unread,
Aug 24, 2015, 2:53:51 PM8/24/15
to play-framework

I'm trying to migrate to dependency injection. Before play 2.4, I have many scala singleton object like this:

object APIs {
  def getSomething() = WS.url(...).get()
}


If I want to let WS be injected, does it means that I have to change all my singleton objects that have used WS into something like this:

@Singleton
class APIs @Inject() (ws: WSClient) {
  def getSomething() = ws.url(...).get()
}


Is this the best practice as changing object to class and add an annotation of @Singleton? This doesn't feel neat to me since it looks like giving up Scala's native singleton object and implement one by the dependency injection library.
Sorry that I have no prior knowledge about DI, this question may be too simple.

Thanks,
pishen

Will Sargent

unread,
Aug 24, 2015, 5:05:19 PM8/24/15
to play-fr...@googlegroups.com
You don't have to use @Singleton.  Just using the @Inject is fine.

--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framewor...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/play-framework/67c7d7e1-32ea-4a56-87fd-610a902c4371%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

pishen tsai

unread,
Aug 24, 2015, 10:44:53 PM8/24/15
to play-framework

Do you have any example?
I would like to know how to use @Inject in Scala's singleton object. In other words, how to avoid using WS in

object APIs {
  def getSomething() = WS.url(...).get()
}

without changing object to class?


Will Sargent於 2015年8月25日星期二 UTC+8上午5時05分19秒寫道:

pishen tsai

unread,
Aug 25, 2015, 1:13:11 AM8/25/15
to play-framework
Sorry, haven't really understand the details of DI, but it seems that when using DI, I can only get an instance of WSClient from class Application, hence I have to pass the reference of this WSClient to every other classes or methods who need to use it?
And it doesn't seems possible to assign this WSClient to a val in a Scala singleton object?
This is not convenience since I have to keep passing the WSClient around instead of putting an import statement at the top of the file. Are there any coding style suggestion for this kind of situation?
By the way, will play.api.libs.ws.WS be deprecated in Play 3.0 so that we have to refactor our code in order to keep upgarding?

Thanks

pishen tsai於 2015年8月25日星期二 UTC+8上午10時44分53秒寫道:
Reply all
Reply to author
Forward
0 new messages