注入 Play 類
你經常需要從框架本身(如 WSClient 或 Configuration)訪問類的例項。你可以在自己的類中注入它們:
class ComplexService @Inject()(
configuration: Configuration,
wsClient: WSClient,
applicationLifecycle: ApplicationLifecycle,
cacheApi: CacheApi,
actorSystem: ActorSystem,
executionContext: ExecutionContext
) {
// Implementation goes here
// you can use all the injected classes :
//
// configuration to read your .conf files
// wsClient to make HTTP requests
// applicationLifecycle to register stuff to do when the app shutdowns
// cacheApi to use a cache system
// actorSystem to use AKKA
// executionContext to work with Futures
}
有些像 ExecutionContext,如果它們被隱式匯入,可能會更容易使用。只需將它們新增到建構函式的第二個引數列表中:
class ComplexService @Inject()(
configuration: Configuration,
wsClient: WSClient
)(implicit executionContext: ExecutionContext) {
// Implementation goes here
// you can still use the injected classes
// and executionContext is imported as an implicit argument for the whole class
}