container.ts
86 lines
| 2.0 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r1 | /* eslint max-classes-per-file: ["error", 20] */ | |
| import { describe, it } from "mocha"; | |||
|
|
r4 | import { Container } from "../Container"; | |
|
|
r7 | import { ContainerServices, DepsMap, Refs, Resolver } from "../interfaces"; | |
|
|
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; | |||
| } | |||
|
|
r7 | declare const resolver: Resolver<Services>; | |
| const foo = resolver("foo", {lazy: true}); | |||
| const mmap = <X extends DepsMap<Services, string>>(m: X) => {}; | |||
| const refs: Refs<Services> = {name: "bar", default: undefined}; | |||
| mmap({ | |||
| fooz: {name: "foo", lazy: false, default: undefined }, | |||
| ooz: "bar" | |||
| }); | |||
|
|
r1 | 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", // зависимость | |||
|
|
r7 | bar: "bar", | |
|
|
r4 | ||
|
|
r7 | $zoo: { name: "foo", lazy: true, } // отложенная активация, | |
|
|
r4 | //фабричный метод | |
| }) | |||
|
|
r7 | .wants({ | |
| zoom: "bar" | |||
| }) | |||
| .factory(({ $zoo, zoo }) => // фабрика получает объект с именованными зависимостями | |||
|
|
r4 | // удобно для деструктурирования | |
|
|
r7 | new Bar($zoo) // создается экземпляр сервиса | |
|
|
r4 | ), | |
| foo: it => it.factory(() => new Foo()), | |||
|
|
r1 | baz: it => it.value(new Foo()) | |
| }) | |||
|
|
r2 | .done({}); | |
|
|
r1 | ||
|
|
r5 | declare const container: Container<object>; | |
| const c2 = config.configure(container); | |||
|
|
r1 | ||
|
|
r5 | c2.resolve("foo"); | |
| declare const m :ContainerServices<{foo: Foo}>["container"]; | |||
| m.resolve("container").resolve("container"); |
