HomeAbout

Inversify Syntax

Basic

Suppose we are creating some service that uses a Symbol

@injectable() // constructor decorator export default class SomeService implements ISomeService { private repository: ISomeRepository; // private property 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; } }

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

Bind

// InjectableClass @injectable class InjectableClass implements IClassType { private external: IExternal; constructor( // where you inject @inject(Symbol) external: IExternal ) { this.external = external; } }
bind<IType>(Symbol) .to(InjectableClass)
AboutContact