Skip to content

Dependency injection

kopecmi8 edited this page Feb 7, 2022 · 3 revisions

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.

Common usage

In Frui.ts is usefull to automatically creates ViewModels, Services and Repositories instances, and provide them to each other.

Example

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.

Factory pattern

Sometimes you need to pass some other parameters to contructor which cannot be served by DI container. Than comes handy to use Factory pattern

Example

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));
    }
}