├── project ├── build.properties └── plugins.sbt ├── src ├── test │ ├── resources │ │ ├── logback-test.xml │ │ └── application.conf │ └── scala │ │ └── scaldi │ │ └── play │ │ ├── PlayConfigInjectorSpec.scala │ │ ├── SlickTest.scala │ │ ├── ControllerInjectorTest.scala │ │ └── PlayConditionSpec.scala └── main │ └── scala │ └── scaldi │ └── play │ ├── ScaldiApplicationLoader.scala │ ├── ControllerComponentsModule.scala │ ├── condition │ └── package.scala │ ├── FakeRouter.scala │ ├── ScaldiInjector.scala │ ├── ControllerInjector.scala │ ├── ScaldiApplicationBuilder.scala │ └── ScaldiBuilder.scala ├── .gitignore ├── .scalafmt.conf ├── README.md ├── .github └── workflows │ ├── clean.yml │ └── ci.yml └── LICENSE /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.6.2 2 | -------------------------------------------------------------------------------- /src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /src/test/resources/application.conf: -------------------------------------------------------------------------------- 1 | test.stringProp = "123" 2 | test.intProp = 456 3 | 4 | play.http.secret.key="QCY?tAnfk?aZ?iwrNwnxIlR6CTf:G3gf:90Latabg@5241AB`R5W:1uDFN];Ik@n" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | # idea 5 | .idea 6 | .idea_modules 7 | 8 | # sbt specific 9 | .bsp 10 | dist/* 11 | target/ 12 | lib_managed/ 13 | src_managed/ 14 | project/boot/ 15 | project/plugins/project/ 16 | 17 | # Scala-IDE specific 18 | .scala_dependencies -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | version = 3.4.3 2 | runner.dialect = scala213 3 | project.git = true 4 | 5 | maxColumn = 120 6 | docstrings.oneline = fold 7 | 8 | align.preset = more 9 | 10 | rewrite.rules = [ 11 | PreferCurlyFors 12 | RedundantBraces # maybe non-idempotent 13 | RedundantParens 14 | SortImports 15 | SortModifiers 16 | ] -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.10") 2 | addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.14.2") 3 | 4 | addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.1.0") 5 | 6 | addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.2") 7 | addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "1.4.1") 8 | addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3") 9 | 10 | addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6") 11 | -------------------------------------------------------------------------------- /src/main/scala/scaldi/play/ScaldiApplicationLoader.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import play.api.ApplicationLoader.Context 4 | import play.api._ 5 | import play.core.WebCommands 6 | import scaldi._ 7 | 8 | class ScaldiApplicationLoader(val builder: ScaldiApplicationBuilder) extends ApplicationLoader { 9 | def this() = this(new ScaldiApplicationBuilder()) 10 | 11 | def load(context: Context): Application = 12 | builder 13 | .in(context.environment) 14 | .loadConfig(context.initialConfiguration) 15 | .prependModule(new Module { 16 | bind[OptionalDevContext] to new OptionalDevContext(context.devContext) 17 | }) 18 | .build() 19 | } 20 | -------------------------------------------------------------------------------- /src/main/scala/scaldi/play/ControllerComponentsModule.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import play.api.http.FileMimeTypes 4 | import play.api.i18n.{Langs, MessagesApi} 5 | import play.api.mvc.{ControllerComponents, DefaultActionBuilder, DefaultControllerComponents, PlayBodyParsers} 6 | import scaldi.Module 7 | 8 | import scala.concurrent.ExecutionContext 9 | 10 | /** Created by dsarosi on 30/6/2017. */ 11 | class ControllerComponentsModule extends Module { 12 | bind[ControllerComponents] to DefaultControllerComponents( 13 | inject[DefaultActionBuilder], 14 | inject[PlayBodyParsers], 15 | inject[MessagesApi], 16 | inject[Langs], 17 | inject[FileMimeTypes], 18 | inject[ExecutionContext] 19 | ) 20 | } 21 | -------------------------------------------------------------------------------- /src/test/scala/scaldi/play/PlayConfigInjectorSpec.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import com.typesafe.config.ConfigFactory 4 | import play.api.Configuration 5 | import scaldi.play.ScaldiApplicationBuilder._ 6 | import scaldi.{Injectable, Injector, Module} 7 | import org.scalatest.matchers.should.Matchers 8 | import org.scalatest.wordspec.AnyWordSpec 9 | 10 | class PlayConfigInjectorSpec extends AnyWordSpec with Matchers { 11 | class DummyService(implicit inj: Injector) extends Injectable { 12 | val strProp = inject[String](identified by "test.stringProp") 13 | val intProp = inject[Int](identified by "test.intProp") 14 | 15 | def hi = s"Hi, str = $strProp, int = ${intProp + 1}" 16 | } 17 | 18 | "Play configuration injector" should { 19 | "inject strings and ints" in { 20 | val testModule = new Module { 21 | binding to new DummyService 22 | } 23 | 24 | withScaldiInj(modules = Seq(testModule), configuration = Configuration(ConfigFactory.load())) { implicit inj => 25 | import Injectable._ 26 | 27 | inject[DummyService].hi should be("Hi, str = 123, int = 457") 28 | } 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/scala/scaldi/play/condition/package.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import play.api.Mode 4 | 5 | import languageFeature.postfixOps 6 | 7 | import scaldi.{Condition, Identifier, Injector} 8 | import scaldi.Injectable._ 9 | import play.api.Mode._ 10 | 11 | /** Provides some Play-specific conditions that can be used in the mappings: 12 | * 13 | *
 bind [MessageService] when (inDevMode or inTestMode) to new SimpleMessageService bind
14 |   * [MessageService] when inProdMode to new OfficialMessageService 
15 | */ 16 | package object condition { 17 | 18 | /** Play application is started in Dev mode */ 19 | def inDevMode(implicit inj: Injector): ModeCondition = ModeCondition(Dev) 20 | 21 | /** Play application is started in Test mode */ 22 | def inTestMode(implicit inj: Injector): ModeCondition = ModeCondition(Test) 23 | 24 | /** Play application is started in Prod mode */ 25 | def inProdMode(implicit inj: Injector): ModeCondition = ModeCondition(Prod) 26 | 27 | case class ModeCondition(mode: Mode)(implicit inj: Injector) extends Condition { 28 | lazy val m: Mode = inject[Mode](Symbol("playMode")) 29 | 30 | override def satisfies(identifiers: List[Identifier]): Boolean = m == mode 31 | override val dynamic = false 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/scala/scaldi/play/SlickTest.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import java.io.StringReader 4 | 5 | import com.typesafe.config.ConfigFactory 6 | import play.api.Configuration 7 | import play.api.db.slick.DatabaseConfigProvider 8 | import scaldi.Injectable 9 | import scaldi.play.ScaldiApplicationBuilder._ 10 | import slick.jdbc.JdbcProfile 11 | import org.scalatest.matchers.should.Matchers 12 | import org.scalatest.wordspec.AnyWordSpec 13 | 14 | class SlickTest extends AnyWordSpec with Matchers with Injectable { 15 | "Slick Plugin" should { 16 | "initialized and injected correctly" in { 17 | val config = Configuration(ConfigFactory.parseReader(new StringReader(""" 18 | |slick.dbs.default.driver="slick.driver.H2Driver$" 19 | |slick.dbs.default.db.driver=org.h2.Driver 20 | |slick.dbs.default.db.url="jdbc:h2:mem:play;MODE=MYSQL;TRACE_LEVEL_SYSTEM_OUT=2" 21 | |slick.dbs.default.db.user=sa 22 | |slick.dbs.default.db.password="" 23 | |slick.dbs.default.db.connectionPool=disabled 24 | |slick.dbs.default.db.keepAliveConnection=true 25 | | 26 | |play.evolutions.db.default.autoApply = true 27 | |play.evolutions.db.default.autoApplyDowns = true 28 | |play.evolutions.autocommit=true 29 | """.stripMargin))) 30 | 31 | withScaldiInj(configuration = config) { implicit inj => 32 | inject[DatabaseConfigProvider].get[JdbcProfile] 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/scala/scaldi/play/FakeRouter.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import play.api.inject.RoutesProvider 4 | import play.api.mvc.{Handler, RequestHeader} 5 | import play.api.routing.Router 6 | import play.api.routing.Router.Routes 7 | import scaldi.Module 8 | 9 | import scala.runtime.AbstractPartialFunction 10 | 11 | class FakeRouterModule(fakeRoutes: PartialFunction[(String, String), Handler]) extends Module { 12 | bind[Router] to new FakeRouter(inject[RoutesProvider].get)(fakeRoutes) 13 | } 14 | 15 | object FakeRouterModule { 16 | def apply(fakeRoutes: PartialFunction[(String, String), Handler]) = new FakeRouterModule(fakeRoutes) 17 | } 18 | 19 | class FakeRouter(fallback: Router)(fakeRoutes: PartialFunction[(String, String), Handler]) extends Router { 20 | val routes: Routes = new AbstractPartialFunction[RequestHeader, Handler] { 21 | override def applyOrElse[A <: RequestHeader, B >: Handler](rh: A, default: A => B) = 22 | fakeRoutes.applyOrElse((rh.method, rh.path), (_: (String, String)) => default(rh)) 23 | def isDefinedAt(rh: RequestHeader) = fakeRoutes.isDefinedAt((rh.method, rh.path)) 24 | } orElse new AbstractPartialFunction[RequestHeader, Handler] { 25 | override def applyOrElse[A <: RequestHeader, B >: Handler](rh: A, default: A => B) = 26 | fallback.routes.applyOrElse(rh, default) 27 | def isDefinedAt(x: RequestHeader) = fallback.routes.isDefinedAt(x) 28 | } 29 | 30 | def documentation: Seq[(String, String, String)] = fallback.documentation 31 | def withPrefix(prefix: String) = new FakeRouter(fallback.withPrefix(prefix))(fakeRoutes) 32 | } 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Scaldi-Play 2 | 3 | ![Continuous Integration](https://github.com/scaldi/scaldi-play/workflows/Continuous%20Integration/badge.svg) 4 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.scaldi/scaldi-play_2.13/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.scaldi/scaldi-play_2.13) 5 | 6 | [Scaldi](https://github.com/scaldi/scaldi) integration for Play framework 7 | 8 | Documentation hosting is in flux. Please refer to 9 | The Scaldi documentation DNS record ownership is in flux. 10 | Until that is resolved, you may need to rely on the original project's documentation. 11 | You can find an archive of the original project's homepage 12 | [here](https://web.archive.org/web/20190616212058/http://scaldi.org/), or jump directly 13 | to the documentation 14 | [here](https://web.archive.org/web/20190618005634/http://scaldi.org/learn). Due to it 15 | being an archived website, some of the links on it may not work properly. 16 | 17 | ## Adding Scaldi-Play in Your Build 18 | 19 | SBT Configuration (Play 2.7.x and Play 2.8.x): 20 | ```sbtshell 21 | libraryDependencies += "org.scaldi" %% "scaldi-play" % x.y.z 22 | ``` 23 | 24 | SBT Configuration (Play 2.6.x): 25 | ```sbtshell 26 | libraryDependencies += "org.scaldi" %% "scaldi-play" % "0.5.17" 27 | ``` 28 | 29 | SBT Configuration (Play 2.5.x): 30 | ```sbtshell 31 | libraryDependencies += "org.scaldi" %% "scaldi-play" % "0.5.15" 32 | ``` 33 | 34 | SBT Configuration (Play 2.3.x): 35 | ```sbtshell 36 | libraryDependencies += "org.scaldi" %% "scaldi-play-23" % "0.5.6" 37 | ``` 38 | 39 | ## License 40 | 41 | **scaldi-play** is licensed under [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). 42 | -------------------------------------------------------------------------------- /src/main/scala/scaldi/play/ScaldiInjector.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import play.utils.Threads 4 | import play.api.inject.{BindingKey, Injector => PlayInjector} 5 | import scaldi.Injectable.noBindingFound 6 | import scaldi._ 7 | 8 | import scala.collection.concurrent.TrieMap 9 | import scala.reflect.ClassTag 10 | 11 | class ScaldiInjector(useCache: Boolean, classLoader: ClassLoader)(implicit inj: Injector) extends PlayInjector { 12 | private val cache = TrieMap[BindingKey[_], () => Any]() 13 | 14 | def instanceOf[T](implicit ct: ClassTag[T]): T = 15 | instanceOf(ct.runtimeClass.asInstanceOf[Class[T]]) 16 | 17 | def instanceOf[T](clazz: Class[T]): T = 18 | instanceOf(BindingKey(clazz)) 19 | 20 | def instanceOf[T](key: BindingKey[T]): T = 21 | if (useCache) { 22 | cache 23 | .getOrElse( 24 | key, { 25 | val (actual, allowedToCache, ids) = getActualBinding(key) 26 | val valueFn = () => actual getOrElse noBindingFound(ids) 27 | 28 | if (allowedToCache) 29 | cache(key) = valueFn 30 | 31 | valueFn 32 | } 33 | )() 34 | .asInstanceOf[T] 35 | } else { 36 | val (actual, _, ids) = getActualBinding(key) 37 | 38 | actual map (_.asInstanceOf[T]) getOrElse noBindingFound(ids) 39 | } 40 | 41 | private def getActualBinding(key: BindingKey[_]): (Option[Any], Boolean, List[Identifier]) = 42 | Threads.withContextClassLoader(classLoader) { 43 | val (_, identifiers) = ScaldiBuilder.identifiersForKey(key) 44 | val binding = inj getBinding identifiers 45 | 46 | binding map (b => (b.get, b.isCacheable, identifiers)) getOrElse noBindingFound(identifiers) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/test/scala/scaldi/play/ControllerInjectorTest.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import scaldi.{Injectable, Injector, Module} 4 | import play.api.mvc._ 5 | import play.api.Environment 6 | import play.api.Mode.Test 7 | import scaldi.Injectable.inject 8 | import scaldi.play.ScaldiApplicationBuilder.withScaldiInj 9 | import org.scalatest.matchers.should.Matchers 10 | import org.scalatest.wordspec.AnyWordSpec 11 | 12 | class ControllerInjectorTest extends AnyWordSpec with Matchers with Injectable { 13 | 14 | class UserModule extends Module { 15 | 16 | binding to new TestInjectedController2 { 17 | override val name = "in user module" 18 | } 19 | 20 | bind[String] identifiedBy Symbol("dep") to "dep" 21 | 22 | bind[Environment] to Environment.simple() 23 | } 24 | 25 | "ControllerInjector" should { 26 | 27 | withScaldiInj( 28 | modules = Seq(new UserModule, new ControllerComponentsModule, new ControllerInjector), 29 | environment = Environment.simple(mode = Test) 30 | ) { implicit inj => 31 | "create injected controllers with implicit injector" in { 32 | inject[TestInjectedController1].dep should be("dep-ic1") 33 | } 34 | 35 | "use explicitly defined bindings for injected controllers" in { 36 | val c2 = inject[TestInjectedController2] 37 | 38 | c2.dep should be("dep-ic2") 39 | c2.name should be("in user module") 40 | } 41 | 42 | "create abstract controllers with implicit injector" in { 43 | inject[TestAbstractController1].dep should be("dep-ac1") 44 | } 45 | 46 | } 47 | } 48 | 49 | } 50 | 51 | class TestInjectedController1(implicit inj: Injector) extends InjectedController with Injectable { 52 | val dep = inject[String](Symbol("dep")) + "-ic1" 53 | } 54 | class TestInjectedController2(implicit inj: Injector) extends InjectedController with Injectable { 55 | val dep = inject[String](Symbol("dep")) + "-ic2" 56 | val name = "test" 57 | } 58 | 59 | class TestAbstractController1(implicit inj: Injector, controllerComponents: ControllerComponents) 60 | extends AbstractController(controllerComponents) 61 | with Injectable { 62 | val dep = inject[String](Symbol("dep")) + "-ac1" 63 | } 64 | -------------------------------------------------------------------------------- /src/test/scala/scaldi/play/PlayConditionSpec.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import ScaldiApplicationBuilder._ 4 | import play.api.Environment 5 | import scaldi.Module 6 | import scaldi.play.condition._ 7 | import scaldi.Injectable._ 8 | import play.api.Mode._ 9 | import org.scalatest.matchers.should.Matchers 10 | import org.scalatest.wordspec.AnyWordSpec 11 | 12 | class PlayConditionSpec extends AnyWordSpec with Matchers { 13 | 14 | "Play Condition" should { 15 | "inject bindings based on the correct mode" in { 16 | class TestModule extends Module { 17 | bind[String] identifiedBy Symbol("test") when inTestMode to "test" 18 | bind[String] identifiedBy Symbol("test") when inDevMode to "dev" 19 | bind[String] identifiedBy Symbol("test") when inProdMode to "prod" 20 | } 21 | 22 | withScaldiInj(modules = Seq(new TestModule), environment = Environment.simple(mode = Test)) { implicit inj => 23 | inject[String](Symbol("test")) should be("test") 24 | } 25 | 26 | withScaldiInj(modules = Seq(new TestModule), environment = Environment.simple(mode = Dev)) { implicit inj => 27 | inject[String](Symbol("test")) should be("dev") 28 | } 29 | 30 | withScaldiInj(modules = Seq(new TestModule), environment = Environment.simple(mode = Prod)) { implicit inj => 31 | inject[String](Symbol("test")) should be("prod") 32 | } 33 | } 34 | 35 | "not initialize eager bindings id false" in { 36 | var testInit = false 37 | var devInit = false 38 | var prodInit = false 39 | 40 | class TestModule extends Module { 41 | bind[String] identifiedBy Symbol("test") when inTestMode toNonLazy "test" initWith (_ => testInit = true) 42 | bind[String] identifiedBy Symbol("test") when inDevMode toNonLazy "dev" initWith (_ => devInit = true) 43 | bind[String] identifiedBy Symbol("test") when inProdMode toNonLazy "prod" initWith (_ => prodInit = true) 44 | } 45 | 46 | withScaldiApp(modules = Seq(new TestModule), environment = Environment.simple(mode = Dev)) { 47 | testInit should be(false) 48 | devInit should be(true) 49 | prodInit should be(false) 50 | } 51 | } 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /.github/workflows/clean.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Clean 9 | 10 | on: push 11 | 12 | jobs: 13 | delete-artifacts: 14 | name: Delete Artifacts 15 | runs-on: ubuntu-latest 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | steps: 19 | - name: Delete artifacts 20 | run: | 21 | # Customize those three lines with your repository and credentials: 22 | REPO=${GITHUB_API_URL}/repos/${{ github.repository }} 23 | 24 | # A shortcut to call GitHub API. 25 | ghapi() { curl --silent --location --user _:$GITHUB_TOKEN "$@"; } 26 | 27 | # A temporary file which receives HTTP response headers. 28 | TMPFILE=/tmp/tmp.$$ 29 | 30 | # An associative array, key: artifact name, value: number of artifacts of that name. 31 | declare -A ARTCOUNT 32 | 33 | # Process all artifacts on this repository, loop on returned "pages". 34 | URL=$REPO/actions/artifacts 35 | while [[ -n "$URL" ]]; do 36 | 37 | # Get current page, get response headers in a temporary file. 38 | JSON=$(ghapi --dump-header $TMPFILE "$URL") 39 | 40 | # Get URL of next page. Will be empty if we are at the last page. 41 | URL=$(grep '^Link:' "$TMPFILE" | tr ',' '\n' | grep 'rel="next"' | head -1 | sed -e 's/.*.*//') 42 | rm -f $TMPFILE 43 | 44 | # Number of artifacts on this page: 45 | COUNT=$(( $(jq <<<$JSON -r '.artifacts | length') )) 46 | 47 | # Loop on all artifacts on this page. 48 | for ((i=0; $i < $COUNT; i++)); do 49 | 50 | # Get name of artifact and count instances of this name. 51 | name=$(jq <<<$JSON -r ".artifacts[$i].name?") 52 | ARTCOUNT[$name]=$(( $(( ${ARTCOUNT[$name]} )) + 1)) 53 | 54 | id=$(jq <<<$JSON -r ".artifacts[$i].id?") 55 | size=$(( $(jq <<<$JSON -r ".artifacts[$i].size_in_bytes?") )) 56 | printf "Deleting '%s' #%d, %'d bytes\n" $name ${ARTCOUNT[$name]} $size 57 | ghapi -X DELETE $REPO/actions/artifacts/$id 58 | done 59 | done 60 | -------------------------------------------------------------------------------- /src/main/scala/scaldi/play/ControllerInjector.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import play.api.Environment 4 | import play.api.mvc._ 5 | import scaldi._ 6 | import scaldi.util.ReflectionHelper._ 7 | 8 | import java.lang.reflect.InvocationTargetException 9 | import scala.reflect.runtime.universe.{runtimeMirror, typeTag, Type} 10 | 11 | /**

Injector for the Play applications that creates controller bindings on the fly. The preferred way to use it is by 12 | * adding it to the module composition at the very end, so that it would be possible to override default instantiation 13 | * strategy in user-defined modules. 14 | * 15 | *

Here is an example: 16 | * 17 | *

 object Global extends GlobalSettings with ScaldiSupport { def applicationModule = new
18 |   * UserModule :: new DbModule :: new ControllerInjector } 
19 | */ 20 | class ControllerInjector 21 | extends MutableInjectorUser 22 | with InjectorWithLifecycle[ControllerInjector] 23 | with ShutdownHookLifecycleManager { 24 | 25 | private var bindings: Set[(List[Identifier], Option[BindingWithLifecycle])] = Set.empty 26 | 27 | def getBindingInternal(identifiers: List[Identifier]): Option[BindingWithLifecycle] = identifiers match { 28 | case TypeTagIdentifier(tpe) :: Nil 29 | if (tpe safe_<:< typeTag[InjectedController].tpe) || (tpe safe_<:< typeTag[AbstractController].tpe) => 30 | bindings.find(b => Identifier.sameAs(b._1, identifiers)) map (_._2) getOrElse { 31 | this.synchronized { 32 | bindings.find(b => Identifier.sameAs(b._1, identifiers)) map (_._2) getOrElse { 33 | val binding = createBinding(tpe, identifiers) 34 | bindings = bindings + binding 35 | binding._2 36 | } 37 | } 38 | } 39 | case _ => None 40 | } 41 | 42 | private def createBinding( 43 | tpe: Type, 44 | identifiers: List[Identifier] 45 | ): (List[Identifier], Option[BindingWithLifecycle]) = { 46 | val controller = 47 | tpe.decls 48 | .filter(_.isMethod) 49 | .map(_.asMethod) 50 | .find(m => 51 | m.isConstructor && (m.paramLists match { 52 | case List(Nil, List(injectorType, paramType)) 53 | if (tpe safe_<:< typeTag[AbstractController].tpe) 54 | && injectorType.isImplicit 55 | && (injectorType.typeSignature safe_<:< typeTag[Injector].tpe) 56 | && injectorType.isImplicit && (paramType.typeSignature safe_<:< typeTag[ControllerComponents].tpe) => 57 | true 58 | case List(Nil, List(injectorType)) 59 | if (tpe safe_<:< typeTag[InjectedController].tpe) 60 | && injectorType.isImplicit 61 | && (injectorType.typeSignature safe_<:< typeTag[Injector].tpe) => 62 | true 63 | case _ => false 64 | }) 65 | ) 66 | .map { constructor => 67 | import Injectable._ 68 | 69 | val env = inject[Environment] 70 | val mirror = runtimeMirror(env.classLoader) 71 | val constructorMirror = mirror.reflectClass(tpe.typeSymbol.asClass).reflectConstructor(constructor) 72 | 73 | try 74 | constructor.paramLists match { 75 | case List(Nil, List(_, _)) => constructorMirror(injector, inject[ControllerComponents]) 76 | case List(Nil, List(_)) => 77 | val instance = constructorMirror(injector) 78 | instance.asInstanceOf[InjectedController].setControllerComponents(inject[ControllerComponents]) 79 | instance 80 | case List(Nil) => constructorMirror() 81 | } 82 | catch { 83 | case e: InvocationTargetException => throw e.getCause 84 | } 85 | } 86 | 87 | identifiers -> controller.map(c => LazyBinding(Some(() => c), identifiers)) 88 | } 89 | 90 | def getBindingsInternal(identifiers: List[Identifier]): List[BindingWithLifecycle] = 91 | getBindingInternal(identifiers).toList 92 | 93 | protected def init(lifecycleManager: LifecycleManager): () => Unit = () => () 94 | } 95 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Continuous Integration 9 | 10 | on: 11 | pull_request: 12 | branches: ['**'] 13 | push: 14 | branches: ['**'] 15 | tags: [v*] 16 | 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | 20 | jobs: 21 | build: 22 | name: Build and Test 23 | strategy: 24 | matrix: 25 | os: [ubuntu-latest] 26 | scala: [2.12.15, 2.13.8] 27 | java: [adopt-hotspot@8, adopt-hotspot@11] 28 | runs-on: ${{ matrix.os }} 29 | steps: 30 | - name: Checkout current branch (full) 31 | uses: actions/checkout@v2 32 | with: 33 | fetch-depth: 0 34 | 35 | - name: Setup Java (adopt-hotspot@8) 36 | if: matrix.java == 'adopt-hotspot@8' 37 | uses: actions/setup-java@v2 38 | with: 39 | distribution: adopt-hotspot 40 | java-version: 8 41 | 42 | - name: Setup Java (adopt-hotspot@11) 43 | if: matrix.java == 'adopt-hotspot@11' 44 | uses: actions/setup-java@v2 45 | with: 46 | distribution: adopt-hotspot 47 | java-version: 11 48 | 49 | - name: Cache sbt 50 | uses: actions/cache@v2 51 | with: 52 | path: | 53 | ~/.sbt 54 | ~/.ivy2/cache 55 | ~/.coursier/cache/v1 56 | ~/.cache/coursier/v1 57 | ~/AppData/Local/Coursier/Cache/v1 58 | ~/Library/Caches/Coursier/v1 59 | key: ${{ runner.os }}-sbt-cache-v2-${{ hashFiles('**/*.sbt') }}-${{ hashFiles('project/build.properties') }} 60 | 61 | - run: sbt ++${{ matrix.scala }} scalafmtCheckAll 62 | 63 | - name: Check that workflows are up to date 64 | run: sbt ++${{ matrix.scala }} githubWorkflowCheck 65 | 66 | - name: Build project 67 | run: sbt ++${{ matrix.scala }} test 68 | 69 | - name: Compress target directories 70 | run: tar cf targets.tar target project/target 71 | 72 | - name: Upload target directories 73 | uses: actions/upload-artifact@v2 74 | with: 75 | name: target-${{ matrix.os }}-${{ matrix.scala }}-${{ matrix.java }} 76 | path: targets.tar 77 | 78 | publish: 79 | name: Publish Artifacts 80 | needs: [build] 81 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v')) 82 | strategy: 83 | matrix: 84 | os: [ubuntu-latest] 85 | scala: [2.12.15] 86 | java: [adopt-hotspot@8] 87 | runs-on: ${{ matrix.os }} 88 | steps: 89 | - name: Checkout current branch (full) 90 | uses: actions/checkout@v2 91 | with: 92 | fetch-depth: 0 93 | 94 | - name: Setup Java (adopt-hotspot@8) 95 | if: matrix.java == 'adopt-hotspot@8' 96 | uses: actions/setup-java@v2 97 | with: 98 | distribution: adopt-hotspot 99 | java-version: 8 100 | 101 | - name: Setup Java (adopt-hotspot@11) 102 | if: matrix.java == 'adopt-hotspot@11' 103 | uses: actions/setup-java@v2 104 | with: 105 | distribution: adopt-hotspot 106 | java-version: 11 107 | 108 | - name: Cache sbt 109 | uses: actions/cache@v2 110 | with: 111 | path: | 112 | ~/.sbt 113 | ~/.ivy2/cache 114 | ~/.coursier/cache/v1 115 | ~/.cache/coursier/v1 116 | ~/AppData/Local/Coursier/Cache/v1 117 | ~/Library/Caches/Coursier/v1 118 | key: ${{ runner.os }}-sbt-cache-v2-${{ hashFiles('**/*.sbt') }}-${{ hashFiles('project/build.properties') }} 119 | 120 | - name: Download target directories (2.12.15) 121 | uses: actions/download-artifact@v2 122 | with: 123 | name: target-${{ matrix.os }}-2.12.15-${{ matrix.java }} 124 | 125 | - name: Inflate target directories (2.12.15) 126 | run: | 127 | tar xf targets.tar 128 | rm targets.tar 129 | 130 | - name: Download target directories (2.13.8) 131 | uses: actions/download-artifact@v2 132 | with: 133 | name: target-${{ matrix.os }}-2.13.8-${{ matrix.java }} 134 | 135 | - name: Inflate target directories (2.13.8) 136 | run: | 137 | tar xf targets.tar 138 | rm targets.tar 139 | 140 | - env: 141 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} 142 | PGP_SECRET: ${{ secrets.PGP_SECRET }} 143 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 144 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 145 | run: sbt ++${{ matrix.scala }} ci-release 146 | -------------------------------------------------------------------------------- /src/main/scala/scaldi/play/ScaldiApplicationBuilder.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import play.api._ 4 | import play.api.inject.{Injector => PlayInjector, Module => _} 5 | import play.core.{DefaultWebCommands, WebCommands} 6 | import scaldi.{Injectable, Injector, Module} 7 | 8 | /** A builder for creating Applications using Scaldi. */ 9 | final class ScaldiApplicationBuilder( 10 | environment: Environment = Environment.simple(), 11 | configuration: Configuration = Configuration.empty, 12 | modules: Seq[CanBeScaldiInjector] = Seq.empty, 13 | disabled: Seq[Class[_]] = Seq.empty, 14 | loadConfiguration: Environment => Configuration = Configuration.load, 15 | loadModules: (Environment, Configuration) => Seq[CanBeScaldiInjector] = ScaldiBuilder.loadModules 16 | ) extends ScaldiBuilder[ScaldiApplicationBuilder](environment, configuration, modules, disabled) { 17 | def this() = this(environment = Environment.simple()) 18 | 19 | val GlobalAppConfigKey = "play.allowGlobalApplication" 20 | 21 | /** Sets the configuration key to enable/disable global application state */ 22 | def globalApp(enabled: Boolean): ScaldiApplicationBuilder = 23 | configure(GlobalAppConfigKey -> enabled) 24 | 25 | /** Set the initial configuration loader. Overrides the default or any previously configured values. */ 26 | def loadConfig(loader: Environment => Configuration): ScaldiApplicationBuilder = 27 | copy(loadConfiguration = loader) 28 | 29 | /** Set the initial configuration. Overrides the default or any previously configured values. */ 30 | def loadConfig(conf: Configuration): ScaldiApplicationBuilder = loadConfig(_ => conf) 31 | 32 | /** Set the module loader. Overrides the default or any previously configured values. */ 33 | def load(loader: (Environment, Configuration) => Seq[CanBeScaldiInjector]): ScaldiApplicationBuilder = 34 | copy(loadModules = loader) 35 | 36 | /** Override the module loader with the given modules. */ 37 | def load(modules: CanBeScaldiInjector*): ScaldiApplicationBuilder = load((_, _) => modules) 38 | 39 | protected def realInjector: (Injector, PlayInjector) = { 40 | val initialConfiguration = loadConfiguration(environment) 41 | val appConfiguration = configuration withFallback initialConfiguration 42 | 43 | LoggerConfigurator(environment.classLoader).foreach(_.configure(environment)) 44 | 45 | if (appConfiguration.underlying.hasPath("logger")) 46 | ScaldiApplicationBuilder.logger.warn( 47 | "Logger configuration in conf files is deprecated and has no effect. Use a logback configuration file instead." 48 | ) 49 | 50 | val loadedModules = loadModules(environment, appConfiguration) 51 | val cacheControllers = appConfiguration.getOptional[Boolean]("scaldi.controller.cache") getOrElse true 52 | 53 | copy(configuration = appConfiguration) 54 | .appendModule(loadedModules: _*) 55 | .appendModule(new BuiltinScaldiModule(cacheControllers, environment.classLoader, environment.mode)) 56 | .createInjector 57 | } 58 | 59 | /** Create a new Play Application using this configured builder. In order ti get the underlying injector instead, 60 | * please use `buildInj` or `buildPlayInj` instead. 61 | */ 62 | def build(): Application = realInjector._2.instanceOf[Application] 63 | 64 | /** Create a new Scaldi Injector for an Application using this configured builder. */ 65 | def buildInj(): Injector = realInjector._1 66 | 67 | /** Create a new Play Injector for an Application using this configured builder. */ 68 | def buildPlayInj(): PlayInjector = realInjector._2 69 | 70 | /** Internal copy method with defaults. */ 71 | private def copy( 72 | environment: Environment = environment, 73 | configuration: Configuration = configuration, 74 | modules: Seq[CanBeScaldiInjector] = modules, 75 | disabled: Seq[Class[_]] = disabled, 76 | loadConfiguration: Environment => Configuration = loadConfiguration, 77 | loadModules: (Environment, Configuration) => Seq[CanBeScaldiInjector] = loadModules 78 | ): ScaldiApplicationBuilder = 79 | new ScaldiApplicationBuilder(environment, configuration, modules, disabled, loadConfiguration, loadModules) 80 | 81 | override protected def newBuilder( 82 | environment: Environment, 83 | configuration: Configuration, 84 | modules: Seq[CanBeScaldiInjector], 85 | disabled: Seq[Class[_]] 86 | ): ScaldiApplicationBuilder = 87 | copy(environment, configuration, modules, disabled) 88 | } 89 | 90 | class BuiltinScaldiModule(cacheControllers: Boolean, classLoader: ClassLoader, mode: Mode) extends Module { 91 | bind[OptionalSourceMapper] to new OptionalSourceMapper(None) 92 | bind[WebCommands] to new DefaultWebCommands 93 | bind[PlayInjector] to new ScaldiInjector(cacheControllers, classLoader) 94 | 95 | binding identifiedBy Symbol("playMode") to mode 96 | } 97 | 98 | object ScaldiApplicationBuilder { 99 | private val logger = Logger(classOf[ScaldiApplicationBuilder]) 100 | 101 | /** Helper function that allows to construct a Play `Application` and execute a function while it's running. */ 102 | def withScaldiApp[T]( 103 | environment: Environment = Environment.simple(), 104 | configuration: Configuration = Configuration.empty, 105 | modules: Seq[CanBeScaldiInjector] = Seq.empty, 106 | disabled: Seq[Class[_]] = Seq.empty, 107 | loadConfiguration: Environment => Configuration = Configuration.load, 108 | loadModules: (Environment, Configuration) => Seq[CanBeScaldiInjector] = ScaldiBuilder.loadModules 109 | )(fn: => T): T = { 110 | val app = 111 | new ScaldiApplicationBuilder(environment, configuration, modules, disabled, loadConfiguration, loadModules) 112 | .appendModule(new Module { 113 | // `play.api.ApplicationLoader.DevContext` not available without a `play.api.ApplicationLoader.Context` 114 | bind[OptionalDevContext] to new OptionalDevContext(None) 115 | }) 116 | .build() 117 | 118 | try { 119 | Play.start(app) 120 | fn 121 | } finally Play.stop(app) 122 | } 123 | 124 | /** Helper function that allows to construct a Play `Application` and execute a function while it's running. This 125 | * variation allows you to also get scaldi `Injector` of this application. 126 | */ 127 | def withScaldiInj[T]( 128 | environment: Environment = Environment.simple(), 129 | configuration: Configuration = Configuration.empty, 130 | modules: Seq[CanBeScaldiInjector] = Seq.empty, 131 | disabled: Seq[Class[_]] = Seq.empty, 132 | loadConfiguration: Environment => Configuration = Configuration.load, 133 | loadModules: (Environment, Configuration) => Seq[CanBeScaldiInjector] = ScaldiBuilder.loadModules 134 | )(fn: Injector => T): T = { 135 | implicit val inj: Injector = 136 | new ScaldiApplicationBuilder(environment, configuration, modules, disabled, loadConfiguration, loadModules) 137 | .appendModule(new Module { 138 | // `play.api.ApplicationLoader.DevContext` not available without a `play.api.ApplicationLoader.Context` 139 | bind[OptionalDevContext] to new OptionalDevContext(None) 140 | }) 141 | .buildInj() 142 | val app = Injectable.inject[Application] 143 | 144 | try { 145 | Play.start(app) 146 | fn(inj) 147 | } finally Play.stop(app) 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /src/main/scala/scaldi/play/ScaldiBuilder.scala: -------------------------------------------------------------------------------- 1 | package scaldi.play 2 | 3 | import play.api._ 4 | import play.api.inject.{Binding => PlayBinding, Injector => PlayInjector, Module => PlayModule, _} 5 | import scaldi._ 6 | import scaldi.jsr330.{AnnotationBinding, AnnotationIdentifier, OnDemandAnnotationInjector} 7 | import scaldi.util.ReflectionHelper 8 | 9 | import java.io.File 10 | import javax.inject._ 11 | import scala.concurrent.Future 12 | import scala.reflect.ClassTag 13 | import scala.reflect.runtime.universe.{typeOf, Type} 14 | 15 | abstract class ScaldiBuilder[Self] protected ( 16 | environment: Environment, 17 | configuration: Configuration, 18 | modules: Seq[CanBeScaldiInjector], 19 | disabled: Seq[Class[_]] 20 | ) { 21 | 22 | /** Set the environment. */ 23 | final def in(env: Environment): Self = copyBuilder(environment = env) 24 | 25 | /** Set the environment path. */ 26 | final def in(path: File): Self = 27 | copyBuilder(environment = environment.copy(rootPath = path)) 28 | 29 | /** Set the environment mode. */ 30 | final def in(mode: Mode): Self = 31 | copyBuilder(environment = environment.copy(mode = mode)) 32 | 33 | /** Set the environment class loader. */ 34 | final def in(classLoader: ClassLoader): Self = copyBuilder(environment = environment.copy(classLoader = classLoader)) 35 | 36 | /** Add additional configuration. */ 37 | final def configure(conf: Configuration): Self = copyBuilder(configuration = conf withFallback configuration) 38 | 39 | /** Add additional configuration. */ 40 | final def configure(conf: Map[String, Any]): Self = configure(Configuration.from(conf)) 41 | 42 | /** Add additional configuration. */ 43 | final def configure(conf: (String, Any)*): Self = configure(conf.toMap) 44 | 45 | /** * Disable modules by class. 46 | */ 47 | final def disable(moduleClasses: Class[_]*): Self = copyBuilder(disabled = disabled ++ moduleClasses) 48 | 49 | /** Disable module by class. */ 50 | final def disable[T](implicit tag: ClassTag[T]): Self = disable(tag.runtimeClass) 51 | final def appendModule(ms: CanBeScaldiInjector*): Self = copyBuilder(modules = modules ++ ms) 52 | final def prependModule(ms: CanBeScaldiInjector*): Self = copyBuilder(modules = ms ++ modules) 53 | 54 | final protected def createInjector: (Injector, PlayInjector) = { 55 | import ScaldiBuilder._ 56 | 57 | try { 58 | val commonBindings = new Module { 59 | bind[PlayInjector] to new ScaldiInjector(false, environment.classLoader) 60 | } 61 | 62 | val enabledModules = modules.map(_.disable(disabled)) 63 | val scaldiInjectors = enabledModules flatMap (_.toScaldi(environment, configuration)) 64 | 65 | implicit val injector: Injector = createScaldiInjector(scaldiInjectors :+ commonBindings, configuration) 66 | 67 | injector -> Injectable.inject[PlayInjector] 68 | } catch { 69 | // unwrap play exceptions that are causes of com.google.inject.CreationException without importing guice 70 | case t: Throwable if t.getCause.isInstanceOf[PlayException] => throw t.getCause 71 | } 72 | } 73 | 74 | /** Internal copy method with defaults. */ 75 | private def copyBuilder( 76 | environment: Environment = environment, 77 | configuration: Configuration = configuration, 78 | modules: Seq[CanBeScaldiInjector] = modules, 79 | disabled: Seq[Class[_]] = disabled 80 | ): Self = 81 | newBuilder(environment, configuration, modules, disabled) 82 | 83 | /** Create a new Self for this immutable builder. Provided by builder implementations. */ 84 | protected def newBuilder( 85 | environment: Environment, 86 | configuration: Configuration, 87 | modules: Seq[CanBeScaldiInjector], 88 | disabled: Seq[Class[_]] 89 | ): Self 90 | } 91 | 92 | object ScaldiBuilder extends Injectable { 93 | def loadModules(environment: Environment, configuration: Configuration): Seq[CanBeScaldiInjector] = { 94 | def doLoadModules(modules: Seq[Any]) = 95 | modules.map { 96 | case playModule: PlayModule => CanBeScaldiInjector.fromPlayModule(playModule) 97 | case inj: Injector => CanBeScaldiInjector.fromScaldiInjector(inj) 98 | case unknown => 99 | throw new PlayException("Unknown module type", s"Module [$unknown] is not a Play module or a Scaldi module") 100 | } 101 | 102 | val (lowPrio, highPrio) = Modules 103 | .locate(environment, configuration) 104 | .partition(m => m.isInstanceOf[BuiltinModule] || m.isInstanceOf[ControllerInjector]) 105 | 106 | doLoadModules(highPrio) ++ doLoadModules(lowPrio) 107 | } 108 | 109 | def createScaldiInjector(injectors: Seq[Injector], config: Configuration): Injector = { 110 | val standard = Seq(TypesafeConfigInjector(config.underlying), new OnDemandAnnotationInjector) 111 | val allInjectors = injectors ++ standard 112 | 113 | implicit val injector: Injector = new MutableInjectorAggregation(allInjectors.toList) 114 | 115 | injector match { 116 | case init: Initializeable[_] => 117 | init.initNonLazy() 118 | case _ => // there is nothing to init 119 | } 120 | 121 | injector match { 122 | case lm: LifecycleManager => 123 | inject[ApplicationLifecycle] addStopHook { () => 124 | lm.destroy() 125 | 126 | Future.successful(()) 127 | } 128 | case _ => // there is nothing to destroy 129 | } 130 | 131 | injector 132 | } 133 | 134 | def convertToScaldiModule(env: Environment, conf: Configuration, playModule: PlayModule): Injector = 135 | toScaldiBindings(playModule.bindings(env, conf).toList) 136 | 137 | /** Convert play DI [[BindingKey]] to scaldi [[Identifier]] s. If using [[Qualifier]] annotations, the qualifier 138 | * annotations must be themselves annotated with @[[Qualifier]] or an error will be thrown. This aligns with JSR330. 139 | * 140 | * This differs from play's [[BindingKey]] documented examples showing qualifier annotations that do not have this 141 | * annotation. 142 | */ 143 | def identifiersForKey[T](key: BindingKey[T]): (Type, List[Identifier]) = { 144 | val mirror = ReflectionHelper.mirror 145 | val keyType = mirror.classSymbol(key.clazz).toType 146 | 147 | // scaldi appears to differ from play's 148 | val qualifier: Option[Identifier] = key.qualifier map { 149 | case QualifierInstance(a: Named) => StringIdentifier(a.value()) 150 | case QualifierInstance(a) => AnnotationIdentifier.forAnnotation(a) 151 | case QualifierClass(clazz) => AnnotationIdentifier(ReflectionHelper.classToType(clazz)) 152 | } 153 | 154 | (keyType, TypeTagIdentifier(keyType) :: qualifier.toList) 155 | } 156 | 157 | def toScaldiBindings(bindings: Seq[PlayBinding[_]]): Injector = { 158 | val mirror = ReflectionHelper.mirror 159 | 160 | val scaldiBindings = (inj: Injector) => 161 | bindings.toList.map { binding => 162 | val scope = binding.scope map (mirror.classSymbol(_).toType) 163 | val singleton = scope.exists(_ =:= typeOf[Singleton]) 164 | val (keyType, identifiers) = identifiersForKey(binding.key) 165 | 166 | binding.target match { 167 | case Some(BindingKeyTarget(key)) if binding.eager => 168 | NonLazyBinding( 169 | Some(() => injectWithDefault[Any](inj, noBindingFound(identifiers))(identifiersForKey(key)._2)), 170 | identifiers 171 | ) 172 | case Some(BindingKeyTarget(key)) if singleton => 173 | LazyBinding( 174 | Some(() => injectWithDefault[Any](inj, noBindingFound(identifiers))(identifiersForKey(key)._2)), 175 | identifiers 176 | ) 177 | case Some(BindingKeyTarget(key)) => 178 | ProviderBinding( 179 | () => injectWithDefault[Any](inj, noBindingFound(identifiers))(identifiersForKey(key)._2), 180 | identifiers 181 | ) 182 | 183 | case Some(ProviderTarget(provider)) => 184 | AnnotationBinding( 185 | instanceOrType = Left(provider), 186 | injector = () => inj, 187 | identifiers = identifiers, 188 | eager = binding.eager, 189 | forcedScope = scope, 190 | bindingConverter = Some(_.asInstanceOf[Provider[AnyRef]].get()) 191 | ) 192 | 193 | case Some(ProviderConstructionTarget(provider)) if binding.eager => 194 | val providerIds = List[Identifier](ReflectionHelper.classToType(provider)) 195 | 196 | NonLazyBinding( 197 | Some(() => injectWithDefault[Provider[_]](inj, noBindingFound(providerIds))(providerIds).get()), 198 | identifiers 199 | ) 200 | case Some(ProviderConstructionTarget(provider)) if singleton => 201 | val providerIds = List[Identifier](ReflectionHelper.classToType(provider)) 202 | 203 | LazyBinding( 204 | Some(() => injectWithDefault[Provider[_]](inj, noBindingFound(providerIds))(providerIds).get()), 205 | identifiers 206 | ) 207 | case Some(ProviderConstructionTarget(provider)) => 208 | val providerIds = List[Identifier](ReflectionHelper.classToType(provider)) 209 | 210 | ProviderBinding( 211 | () => injectWithDefault[Provider[_]](inj, noBindingFound(providerIds))(providerIds).get(), 212 | identifiers 213 | ) 214 | 215 | case Some(ConstructionTarget(impl)) if binding.eager => 216 | val implIds = List[Identifier](ReflectionHelper.classToType(impl)) 217 | 218 | NonLazyBinding(Some(() => injectWithDefault[Any](inj, noBindingFound(implIds))(implIds)), identifiers) 219 | case Some(ConstructionTarget(impl)) if singleton => 220 | val implIds = List[Identifier](ReflectionHelper.classToType(impl)) 221 | 222 | LazyBinding(Some(() => injectWithDefault[Any](inj, noBindingFound(implIds))(implIds)), identifiers) 223 | case Some(ConstructionTarget(impl)) => 224 | val implIds = List[Identifier](ReflectionHelper.classToType(impl)) 225 | 226 | ProviderBinding(() => injectWithDefault[Any](inj, noBindingFound(implIds))(implIds), identifiers) 227 | case None => 228 | AnnotationBinding( 229 | instanceOrType = Right(keyType), 230 | injector = () => inj, 231 | identifiers = identifiers, 232 | eager = binding.eager, 233 | forcedScope = scope 234 | ) 235 | } 236 | } 237 | 238 | new SimpleContainerInjector(scaldiBindings) 239 | } 240 | } 241 | 242 | /** Default empty builder for creating Scaldi-backed Injectors. */ 243 | final class ScaldiInjectorBuilder( 244 | environment: Environment = Environment.simple(), 245 | configuration: Configuration = Configuration.empty, 246 | modules: Seq[CanBeScaldiInjector] = Seq.empty, 247 | disabled: Seq[Class[_]] = Seq.empty 248 | ) extends ScaldiBuilder[ScaldiInjectorBuilder](environment, configuration, modules, disabled) { 249 | def this() = this(environment = Environment.simple()) 250 | 251 | /** Create a Play Injector backed by Scaldi using this configured builder. */ 252 | def build(): PlayInjector = createInjector._2 253 | 254 | /** Create a Scaldi Injector using this configured builder. */ 255 | def buildInj(): Injector = createInjector._1 256 | 257 | protected def newBuilder( 258 | environment: Environment, 259 | configuration: Configuration, 260 | modules: Seq[CanBeScaldiInjector] = Seq.empty, 261 | disabled: Seq[Class[_]] 262 | ): ScaldiInjectorBuilder = 263 | new ScaldiInjectorBuilder(environment, configuration, modules, disabled) 264 | } 265 | 266 | trait CanBeScaldiInjector { 267 | def toScaldi(env: Environment, conf: Configuration): Seq[Injector] 268 | def disable(classes: Seq[Class[_]]): CanBeScaldiInjector 269 | } 270 | 271 | object CanBeScaldiInjector { 272 | import scala.language.implicitConversions 273 | 274 | implicit def fromScaldiInjector(inj: Injector): CanBeScaldiInjector = fromScaldiInjectors(Seq(inj)) 275 | 276 | implicit def fromScaldiInjectors(injectors: Seq[Injector]): CanBeScaldiInjector = new CanBeScaldiInjector { 277 | def toScaldi(env: Environment, conf: Configuration): Seq[Injector] = injectors 278 | def disable(classes: Seq[Class[_]]): CanBeScaldiInjector = fromScaldiInjectors(filterOut(classes, injectors)) 279 | override def toString = s"CanBeScaldiInjector(${injectors.mkString(", ")})" 280 | } 281 | 282 | implicit def fromPlayModule(playModule: PlayModule): CanBeScaldiInjector = fromPlayModules(Seq(playModule)) 283 | 284 | implicit def fromPlayModules(playModules: Seq[PlayModule]): CanBeScaldiInjector = new CanBeScaldiInjector { 285 | def toScaldi(env: Environment, conf: Configuration): Seq[Injector] = 286 | playModules.map(ScaldiBuilder.convertToScaldiModule(env, conf, _)) 287 | def disable(classes: Seq[Class[_]]): CanBeScaldiInjector = fromPlayModules(filterOut(classes, playModules)) 288 | override def toString = s"CanBeScaldiInjector(${playModules.mkString(", ")})" 289 | } 290 | 291 | implicit def fromPlayBinding(binding: PlayBinding[_]): CanBeScaldiInjector = fromPlayBindings(Seq(binding)) 292 | 293 | implicit def fromPlayBindings(bindings: Seq[PlayBinding[_]]): CanBeScaldiInjector = new CanBeScaldiInjector { 294 | def toScaldi(env: Environment, conf: Configuration): Seq[Injector] = Seq(ScaldiBuilder.toScaldiBindings(bindings)) 295 | def disable(classes: Seq[Class[_]]): CanBeScaldiInjector = this // no filtering 296 | override def toString = s"CanBeScaldiInjector(${bindings.mkString(", ")})" 297 | } 298 | 299 | private def filterOut[A](classes: Seq[Class[_]], instances: Seq[A]): Seq[A] = 300 | instances.filterNot(o => classes.exists(_.isAssignableFrom(o.getClass))) 301 | } 302 | --------------------------------------------------------------------------------