我在app/Global.scala
看到了这样的代码,这是我的同事写的
import java.lang.reflect.Constructor
import securesocial.core.RuntimeEnvironment
import securesocial.core.providers._
import securesocial.core.providers.utils.Mailer
import services.UserService
import scala.collection.immutable.ListMap
object Global extends play.api.GlobalSettings {
/**
* The runtime environment for this app.
*/
object MyRuntimeEnvironment extends RuntimeEnvironment.Default[User] {
// override lazy val routes = new CustomRoutesService()
override lazy val userService: UserService = new UserService()
lazy val MailTemplates: MailTemplates = new MailTemplates(this)
override lazy val mailer: Mailer = new Mailer(MailTemplates)
// override lazy val eventListeners = List(new MyEventListener())
override lazy val providers = ListMap(
// oauth 2 client providers
include(new FacebookProvider(routes, cacheService, oauth2ClientFor(FacebookProvider.Facebook))),
// username password
include(new UsernamePasswordProvider(userService, avatarService, passwordHashers))
)
}
/**
* An implementation that checks if the controller expects a RuntimeEnvironment and
* passes the instance to it if required.
*
* This can be replaced by any DI framework to inject it differently.
*
* @param controllerClass
* @tparam A
* @return
*/
override def getControllerInstance[A](controllerClass: Class[A]): A = {
val instance = controllerClass.getConstructors.find { c =>
val params = c.getParameterTypes
params.length == 1 && params(0) == classOf[RuntimeEnvironment[User]]
}.map {
_.asInstanceOf[Constructor[A]].newInstance(MyRuntimeEnvironment)
}
instance.getOrElse(super.getControllerInstance(controllerClass))
}
}
有人认为在playframework中将服务设置为全局值是否合适?
答案 0 :(得分:3)
服务通常是作为无国籍单身人士实施的,所以我会说它没问题。你的问题与一般依赖注入原则有关,而不是与Play相关。
答案 1 :(得分:1)
是。在没有使用依赖注入框架的情况下,这是一种标准的依赖注入模式。它允许您请求类似于Spring请求范围的范围变量。
您的实现看起来像是基于正在运行的SecureSocial示例实现。看到 https://github.com/jaliss/securesocial/blob/master/samples/scala/demo/app/Global.scala