Turn object into singleton in Play

27 views
Skip to first unread message

Malte

unread,
Apr 21, 2016, 5:41:06 PM4/21/16
to scaldi
Hi,

First of all: I love scaldi. Been using it for years now and super happy with it. Thank you for all the work that has been put into it. 

I currently have an object that is quite heavy to instantiate, but it requires access to the current Play app + configuration. I used to just access Play.application etc, but these are deprecated. If I turn it into a class, it will get instantiated in every test that I use it. I would like to not do that. Is there a way to turn an object into a singleton such that it only gets instantiated once for all tests?

object BigObject {
 val app = Play.app
...
}

becomes

@Singleton
class BigObject(implicit inj: Injector) extends Injectable {
val app = inject[Application]
}

?

Yours

Malte

Alexandre Bedrytski

unread,
Apr 23, 2016, 4:08:09 AM4/23/16
to scaldi
Hi Malte,

if you are using bind to syntax in your module for the BigObject, it is automatically a singleton. (if you don't want it to be a singleton, use bind toProvider instead so it would be initiated on each inject)

As you say, the BigObject class uses configuration, you may pass it as a parameter for a constructor. 

bind [BigObject] to new BigObject(inject[Application])

Alex.

Oleg Ilyenko

unread,
Apr 23, 2016, 4:06:29 PM4/23/16
to scaldi
Thanks for kind words, Malte! I agree with Alexandre's suggestion. I just would like to add, that since `BigObject` uses a play `Application` it also will have the same life-cycle. Every time you create a new application in the test, you also need to create an instance of `BigObject` for it.

Malte Bücken

unread,
Apr 23, 2016, 10:08:55 PM4/23/16
to Oleg Ilyenko, scaldi
Awesome, thank you guys for your help!
--
You received this message because you are subscribed to a topic in the Google Groups "scaldi" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/scaldi/SqNPyWL5ZtU/unsubscribe.
To unsubscribe from this group and all its topics, send an email to scaldi+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages