简体   繁体   中英

Handling Inversify @inject() parameters at class instantiation using typescript

Trying to implement a DI using Inversify , it is not clear how I can achieve a class instantiation without any parameters, when having a dependency injection. This is nearly equivalent to angulars DI. In angular one is able to construct classes containing injections without any @Inject parameters.

app.module.ts

import { Container } from 'inversify';

export class AppModule {
  constructor() {
    let container = new Container(); // maybe use { autoBindInjectable: true }
    const instance = new DatabaseService(); // DatabaseService is injectable
  }
}

The root module creates an Inversify Container and which collects all injectable class instantiations. The DatabaseService class should contain all database operations and has an @injectable decorator.

models.ts

import { DatabaseService } from './database.service';
import { inject } from 'inversify';

export class Models {
  constructor(@inject(DatabaseService) dbService: DatabaseService) {}
}

The Models gets the injectable instance of DatabaseService . In another class I now want to create an instance of Models . How can I achieve a class instatiation without any parameters? Like it is in angular.

myclass.ts

import { Models } from './models.component'

export class MyClass {
  constructor() {
    models = new Models() // Want no constructing parameters!
  }
}

Do you have any ideas or suggestions? Thanks!

Instead of using that Inversify you can simply use what is already provided by Angular itself. Create a new module which will handle your app's instances:

@NgModule({
  providers: [
    DatabaseService
  ]
})

export class CoreModule {

  constructor (@Optional() @SkipSelf() private parentModule: CoreModule) {

    if (parentModule) {
      throw new Error('CoreModule already loaded');
    }
  }
}

The check in the constructor there is optional but prevents CoreModule from being loaded twice, ensuring that your injectables only have 1 instance.

Then import this module into AppModule :

@NgModule({
  imports: [
    CoreModule
  ]
})

export class AppModule {}

Now you can drop Inversify altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM