Skip to content

Commit

Permalink
airframe-di: #887 Support bind only lifecycle hooks (#919)
Browse files Browse the repository at this point in the history
  • Loading branch information
xerial committed Feb 1, 2020
1 parent e7321c1 commit db3648d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
16 changes: 16 additions & 0 deletions airframe/src/main/scala/wvlet/airframe/Binder.scala
Expand Up @@ -192,6 +192,22 @@ class Binder[A](val design: Design, val from: Surface, val sourceCode: SourceCod
macro bindToEagerSingletonProvider4[A, D1, D2, D3, D4]
def toEagerSingletonProvider[D1, D2, D3, D4, D5](factory: (D1, D2, D3, D4, D5) => A): DesignWithContext[A] =
macro bindToEagerSingletonProvider5[A, D1, D2, D3, D4, D5]

def onInit(body: A => Unit): DesignWithContext[A] = {
design.withLifeCycleHook[A](LifeCycleHookDesign(ON_INIT, from, body.asInstanceOf[Any => Unit]))
}
def onInject(body: A => Unit): DesignWithContext[A] = {
design.withLifeCycleHook[A](LifeCycleHookDesign(ON_INJECT, from, body.asInstanceOf[Any => Unit]))
}
def onStart(body: A => Unit): DesignWithContext[A] = {
design.withLifeCycleHook[A](LifeCycleHookDesign(ON_START, from, body.asInstanceOf[Any => Unit]))
}
def beforeShutdown(body: A => Unit): DesignWithContext[A] = {
design.withLifeCycleHook[A](LifeCycleHookDesign(BEFORE_SHUTDOWN, from, body.asInstanceOf[Any => Unit]))
}
def onShutdown(body: A => Unit): DesignWithContext[A] = {
design.withLifeCycleHook[A](LifeCycleHookDesign(ON_SHUTDOWN, from, body.asInstanceOf[Any => Unit]))
}
}

class DesignWithContext[A](
Expand Down
Expand Up @@ -48,4 +48,34 @@ class DesignTimeLifeCycleHookTest extends AirSpec {
beforeShutdownTime.get shouldBe 4
shutdownTime.get shouldBe 5
}

def `add lifecycle only`: Unit = {
val v = new AtomicInteger(0)
val d = newSilentDesign
.bind[AtomicInteger].toInstance(v)

val d2 = d
.bind[AtomicInteger]
.onStart { x =>
x.addAndGet(1)
}
.onShutdown { x =>
x.addAndGet(1 << 1)
}
.beforeShutdown { x =>
x.addAndGet(1 << 2)
}
.onInit { x =>
x.addAndGet(1 << 3)
}
.onInject { x =>
x.addAndGet(1 << 4)
}

d2.withSession { s =>
}

v.get() shouldBe 0x1F
}

}

0 comments on commit db3648d

Please sign in to comment.