container.ts
64 lines
| 1.4 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r1 | /* eslint max-classes-per-file: ["error", 20] */ | |
| import { describe, it } from "mocha"; | |||
|
|
r4 | import { Container } from "../Container"; | |
|
|
r1 | import { fluent } from "../traits"; | |
| class Foo { | |||
| foo = "foo"; | |||
| } | |||
| class Bar { | |||
| bar = "bar"; | |||
|
|
r4 | constructor(foo?: () => Foo) { } | |
|
|
r1 | } | |
| interface Services { | |||
| foo: Foo; | |||
| bar?: Bar; | |||
| baz: Foo; | |||
| } | |||
| interface ServicesB { | |||
| // will give errors | |||
| // baz: Bar; | |||
| baz: Foo; | |||
| zoo?: Foo; | |||
| } | |||
| interface SharedServices { | |||
| foo: Foo; | |||
| bar?: Bar; | |||
| baz: Bar; | |||
| } | |||
| const config = fluent() | |||
| .declare<Services>() | |||
| .declare<ServicesB>() | |||
| .register({ | |||
| bar: it => it | |||
|
|
r4 | .lifetime("context") // тип активации, время жизни | |
| .wants({ | |||
| zoo: "zoo", // зависимость | |||
| zoo$: { name: "zoo", lazy: true } // отложенная активация, | |||
| //фабричный метод | |||
| }) | |||
| .factory(({ zoo$ }) => // фабрика получает объект с именованными зависимостями | |||
| // удобно для деструктурирования | |||
| new Bar(zoo$) // создается экземпляр сервиса | |||
| ), | |||
| foo: it => it.factory(() => new Foo()), | |||
|
|
r1 | baz: it => it.value(new Foo()) | |
| }) | |||
|
|
r2 | .done({}); | |
|
|
r1 | ||
|
|
r4 | declare const container: Container<Record<string, never>>; | |
|
|
r1 | const c2 = config.apply(container); | |
|
|
r4 | c2.resolve("foo"); |
