-
Notifications
You must be signed in to change notification settings - Fork 5
Dependency injection
Dependency injection is common programming pattern known from server applications. In Frui.ts we rely on the Inversify library.
Written code is almost dependation free, because we´re using Generator which generates all declaration outside application code, inisde DI registry
.
In Frui.ts is usefull to automatically creates ViewModels, Services and Repositories instances, and provide them to each other.
Inside ExampleScreen you depends on ExampleRepository
which you need to get data from server.
class ExampleScreen extends ScreenBase {
constructor(repository: ExampleRepository) {
super();
}
async fetchData() {
const data = await this.repository.fetchItems();
}
}
You just wrote the constructor and specify type of object which you depends on.
To make this code works you just have to run inversify generator every time you made changes inside constructor to update Inversify declaration files. Thats all. Inversify do a rest for you.
Sometimes you need to pass some other parameters to contructor which cannot be served by DI container. Than comes handy to use Factory pattern
class DetailScreen {
constructor(
private item: DetailEntity,
private repository: ExampleRepository
) {}
static Factory({container}: inversify.Context) {
return (item: DetailEntity) => {
return new DetailScreen(item, container.get(ExampleRepository));
}
}
}
When you want to inject factory do following
class ListScreen extends ConductorOneChildActive {
constructor(private detailScreenFactory: ReturnType<typeof DetailScreen.Factory>) {
super();
}
onItemClick(item: DetailEntity) {
this.tryActivateChild(this.detailScreenFactory(item));
}
}