HomeToolsAbout a20k

Inversify Syntax

Example and Breakdown

Suppose we are creating some service that uses a Symbol

// constructor decorator @injectable() export default class SomeService implements ISomeService { // private property private repository: ISomeRepository; constructor( // parameter decorator @inject(ImplementationTypeSymbol) repository: ISomeRepository, ) { // assign the injected to a private property this.repository = repository; } public async doSomething( someParam: string, ): Promise<SomethingDoneType | null> { const somethingDone: SomethingDoneType = await this.repository.doAThing(someParam); return somethingDone; } }

Constructor Decorator

@injectable()

Private Property

private repository: ISomeRepository;

private respository is the internal property that will be referenced via this.repository in the later part of the class

  • ISomeRepository is the interface data shape that the repository should comply with

Parameter decorator

@inject()

ImplementationTypeSymbol is the symbol to identify the actual implementation to be injected

  • If an underlying implementation needs to be swapped out, this symbol is what triggers the swap

ISomeRepository interface guarantees that swapped implementation should still comply to the expected interface, identical to the previous implementation

© VincentVanKoh