-
-
Notifications
You must be signed in to change notification settings - Fork 0
Usage (typescript)
You have the following application structure:
- index.ts
- foo.ts
- bar.ts
index is the main entry point of your application. Foo is a component (a class) that we want to instantiate inside index. Foo has a dependency to bar and to a logger.
Bar is another component and has a dependency to a logger.
A component can be any Typescript class. Here for example bar.ts file that export Bar class:
bar.ts
export class Bar {
constructor(readonly logger: Console) {
}
helloBar() {
this.logger.log("hello from bar");
}
}
As you can see there isn't any special code or annotation. All you have to do is to export a class that will be called automatically with all the dependencies resolved, in the above case the logger instance.
Foo component is very similar except that it has a dependency to logger and bar:
foo.ts
import {Bar} from "./bar";
export class Foo {
constructor(readonly bar: Bar, readonly logger: Console) {
}
helloFoo() {
this.logger.log("hello from foo");
this.bar.helloBar();
}
}
When Foo will be created an instance of class Bar will be passed. And now take a look at our application entry point, index.ts, where we wire up all the components together:
index.ts
import * as ShelfDependency from "shelf-dependency"
import {Bar} from "./bar";
import {Foo} from "./foo";
const container = new ShelfDependency.Container();
container.register("foo", Foo);
container.register("bar", Bar);
container.register("logger", console);
const foo = container.resolve("foo");
foo.helloFoo();
Basically we create the ShelfDependency.Container and register all the components (Bar, Foo and an object for the logger). Finally we resolve our root class Foo.