Play 2.4 scala I am facing issues getting messages implicit in my code

582 views Asked by At

I am trying to migrate my app from 2.3 to 2.4. In our code base we have used Messages extensively, so any way to remove that will also help. Currently our code is like this

class MyController @Inject() 
(val messagesApi: MessagesApi) extends  Controller  with I18nSupport{

    def methodA() = {
        new MyControllerService.doSomething()
    }
}

class MyControllerService{
    def doSomething()(implicit messages:Messages){
        messages(any_key)
    }
}

When compiling this code i am getting Error:(31, 84) Play 2 Compiler: could not find implicit value for parameter messages: play.api.i18n.Messages compile time error message.

Please help to resolve this issue, any suggestions to improve this kind of problem in better way is most welcome.

2

There are 2 answers

0
Soroosh Sarabadani On

Do it in this way :

class MyController @Inject() 
(val messagesApi: MessagesApi) extends  Controller  with I18nSupport{

    def methodA() = { request =>
        implicit val messages = messageApi.prefered(request)
        new MyControllerService.doSomething()
    }
}

class MyControllerService{
    def doSomething()(implicit messages:Messages){
        messages(any_key)
    }
}

or you can pass created messages object directly in this way:

new MyControllerService.doSomething()(messages)
0
Jenny On

You need to have an implicit request in your Action and the imports for "inject" like so:

package controllers

import javax.inject.Inject
import javax.inject._
import play.api.i18n.{ I18nSupport, MessagesApi, Messages, Lang }
import play.api._
import play.api.mvc._

class Application @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {

  def home() = Action { implicit request =>
    Ok(views.html.home()).as(HTML)
  }
}

in addition, you need to enable the injected router in your build.sbt:

routesGenerator := InjectedRoutesGenerator