classFoo classBar{ var x: Int = _ var y: Int = _ } objectBaz classQux(foo: Foo)
objectMainextendsApp{ // register Foo to self constructor in Transient scope Container.register[Foo].toSelf.inTransientScope() // register Bar to self constructor in Singleton scope Container.register[Bar].toSelf.inSingletonScope() // register Baz as well Container.register[Baz.type].toSelf.inSingletonScope() // register a constructor with parameters Container.register[Qux].toConstructor(classOf[Foo]).inTransientScope() // register a constant value Container.register("A Number").toValue(123).inSingletonScope() // register a factory val barX = 1 val barY = 2 Container.register[Int]("Bar.x").toValue(barX).inSingletonScope() Container.register[Int]("Bar.y").toValue(barY).inSingletonScope() val factory: Factory[Bar] = Container => { // do anything you want val bar = newBar bar.x = Container.resolve[Int]("Bar.x") bar.y = Container.resolve[Int]("Bar.y") bar } Container.register[Bar].toFactory(factory).inTransientScope() // register to another service (registry) Container.register[Foo].toSelf.inTransientScope() // target service Container.register("AnotherFoo").toService[Foo] }
objectMainextendsApp{ // register to value in Transient Container.register("AString") -> "Hello IOC" // register to constructor/class in Transient Container.register[Foo] -> classOf[Foo] // register to constructor/class in Singleton Container.register[Bar] := classOf[Bar] // register to self Container.register[Baz.type] -> Self // register to a constructor with parameters Container.register[Qux] -> New(classOf[Foo]) // register to factory Container.register[Bar] ~> factory // register to service Container.register("AnotherString") >> "AString" }
动态获取
1 2 3 4 5 6 7 8 9 10
import space.controlnet.lightioc.Container
objectMainextendsApp{ // resolve by type val foo: Foo = Container.resolve[Foo] // resolve by string val str: String = Container.resolve[String]("AString") // resolve by factory val bar: Bar = Container.resolve[Bar] }