I am trying to deal with dependency injected objects in Scala template (I am using Java-based Play 2.5).
I have a system of templates, where I have layout template with minimal HTML base and that one is included by almost all other HTML templates which are constructing the rest of the HTML body.
In the template, I am also including top menu with the "Logout" button and also there is a name of currently logged user.
I have a singleton object called LocalAuthenticator which is delivering the User object containing username. So far I was using dependency injection using helper Scala object like this
object LocalAuthenticator {
private val cache = Application.instanceCache[core.security.LocalAuthenticator]
object Implicits {
implicit def localAuth(implicit application: Application): core.security.LocalAuthenticator = cache(application) }
}
Then I was able to access LocalAuthenticator from template using this construct
@import play.api.Play.current
@import scala.LocalAuthenticator.Implicits._
Logged in user is: @localAuth.getCurrentUser().name
This was working in 2.4, however 2.5 is complaining about play.api.Play.current
to be deprecated as it uses static context.
I know that the correct approach is to inject LocalAuthenticator to Controller and pass it to template, however this object should be present in all templates and it is very annoying to inject it to every controller.
Is there any way how to inject a singleton class into template directly?
I was trying to get injector in helper object in order to get singleton, but that could be done only if I have Play Application
object. And that could be retrieved only using DI. So I am running in circles :-)