Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    Thomas Chiantia
    But container makes easier to create dependency
    Yes, container makes it easier to create dependency, but are you really need to run real implementation of your dependencies? What you will do if this dependency execute some intensive computation or something like it?
    Joel Day
    If I have a class that implements "IWeapon", where it wraps a different implementation of IWeapon, injected with a constraint?
    Essentially, I want my wrapped instance to have its dependencies resolved, followed by my wrapper, and then for subsequent requests for IWeapon to resolve to the wrapper.
    Currently with either a named target or a whenInjectedInto, there is still an ambiguous match error.
    Is that a bug or is the scenario not supported?
    Thomas Chiantia
    @AlexHladin I think I am using container to get around Typescript type checker. So that is probably not a good reason to use container for dependency creation. Another trick to create fake depenencies that will never be called because of mocks is to use '!' syntax.
    import {Uut} from "./uut";
    import {Thing} from "./place";
    const mockDependency!: MockDependency // (!) not real dependency
    const uutDependency = new Thing (mockDependency);
    const uut = new Uut(uutDependency);
    // ...
    @TomzBench I really like creating a fake dependency. In my projects, I prefer to use fake dependencies, for example
    test('..', () => {
      const dependency = {
           someFunction = jest.fn()
      const a = new A(dependency)
      expect(dependency.someFunction).toHaveBeenNthCalledWith(1, ....);
    @joelday could you provide some examples?
    Thomas Chiantia
    According to best practice guide, it says to avoid singletons. All of my database services are singletons because I don't want to create a furry of db connections. The default scope in nestjs containers seem to be singletons for that reason. The good practice guide doesn't explain the reasoning behind not using singletons. ( ...So what am i missing about using singletons? So far I only use singletons for stateless utility methods and database services only. Perhaps this can be added to the best practice guides as an exception, unless I am missing something...
    Hey guys, quick question regarding Once an authProvider is configured, server middleware is executed after this. Is there a way to reverse this? Also, does anyone know why the authProvider getUser parameters contain next? Even though a Principal is returned?
    Chad Cravens

    Hey all! New to inversify, and it seems like I'm able to bind my implementation class, like so:

    container = new Container();

    The service runs when I call it like this:

    container.get<MyService>(SERVICES.MyService).hi(); // this runs the MyServiceImpl.hi() method
    However, I get "undefined" when trying to @inject it into a controller class like this:
    export class MyController {
      constructor(@inject(SERVICES.MyService) private myService: MyService) {
        console.log(this.myService); // undefined
    @sanex3339 Are you figure it out?


    Hi. What is the best way to do type safe class members initialization without constructor? Because i want pass to constructor only injectable dependencies.

    For example:

    class Foo implements IFoo {
        private valueA;
        private valueB;
        private bar: IBar;
        constructor(@inject(...) bar: IBar) {...
   = bar;
        public initialize(valueA: number, valueB: number) {
            this.valueA = valueA;
            this.valueB = valueB;
            // i want to make this initialization required and type safe and nice integrate it with Inversify.js
        public getSum() {
            return this.valueA + this.valueB;
    vitekob 249
    Hello everyone
    Could anyone help with provide and injectLazy decorators in inversify typescript project please?
    Here's StackOverflow question
    George Tsomlektsis
    Any idea on why is a multiInject returning an object instead of a List?

    I have an interface

    export interface ICommand {
        commandName: string
        subcommands: ICommand[]
        execute(message: Message, args: string[] | undefined): Promise<void>
        onExecuted(message: Message, args: string[]): Promise<void>

    And the abstract class

    export abstract class Command implements ICommand {
        commandName!: string
        subcommands: ICommand[] = []
        @inject(TYPES.MessageListenerLogger) logger!: pino.Logger
        public async execute(message: Message, args: string[]) {
        public abstract async onExecuted(
            message: Message,
            args: string[]
        ): Promise<void>

    Then I have a "CommandTournament" class that extends that Command abstract class
    and 2 "SubcommandCreate", "SubcommandList" classes that also extend the Command abstract class
    I need to have those 2 subcommands inside the command tournament class

    The root comp is :


    And the CommandTournament constructor is:

            tournamentRepository: TournamentRepository,
            @multiInject(TYPES.Command) @named("CommandTournament") subcommands: ICommand[]
        ) {
           function ommited 

    however in the constructor the multiinject is an object instead of a ICommand[]

    @UltraWelfare .whenTargetNamed("CommandTournament") is the same in both
    George Tsomlektsis
    Isn't that what you should do in order to inject an array?
    I need both classes in the array
    Should I have a different TYPE for it and then not use whenTargetNamed ?
    test this
    George Tsomlektsis
    I need to bind class SubcommandCreate and SubcommandList to an array so that I can inject it in CommandTournament
    CommandTournament basically needs an array of these 2 classes :D

    Should I have a different TYPE for it and then not use whenTargetNamed ?

    I did what I said and it worked

    Adrián Darío Hidalgo Flores
    Someone knows how can I apply an Inyection like angular? example:
    constructor(private someService:  SomeService)
    @AiusDa just add @inject(TYPES...) annotation
    Kamil Solecki
    I've noticed that when using a custom AuthProvider, req.cookies are not available - which would indicate that the authProvider runs before the middlewares do
    is that the case, and if so, what is the reasoning behind it?
    And if it is, is there a workaround to force other middlewares to load before the Auth Provider?
    I have further confirmed this by running various checks, it seems that the AuthProvider is invoked before other middlewares are
    Kamil Solecki
    I also found out that when passing a custom express app to the inversify server constructor, the middlewares are invoked before the auth provider, but when the app is configured through .setConfig(), they run after it.
    I wonder if that is a design choice, as it seems a bit finnicky
    Kamil Solecki
    nvm, it already is in issues: inversify/InversifyJS#1079
    Dominic Robinson
    Hello - Is there a way to use contextual bindings when binding with .toSelf() - I'm stuck doing self bindings due to type-graphql and the way it calls the container. I'm trying to inject a service into a middleware class and provide a specific implemenation depending on the resolver it was called from. whenParentNamed does not appear to work and whenMatched - reveals parentRequest is null.

    I am trying to reuse the MongoDB inversify-express-example but without using the inversify-express-utils (removing the controller decorators and the InversifyExpressServer from the app) I am having a problem to register the container.

    In /controller/user.ts

    Import { injectable, inject } from 'inversify';
    import { User } from '../models/user';
    //I created a an interface for the UserService
    import { IUserService } from '../service/user';
    import { TYPES } from '../constant/types';
    export class UserController{
      private userService: IUserService;
      constructor(@inject(TYPES.IUserService) userService: IUserService) 
        this.userService = userService;
      public getUsers(): Promise<User[]> {
        return this.userService.getUsers();

    Created /controller/toute.ts

    import { Router } from 'express'
    import { container } from '../di'
    import { TYPES } from '../constant/types'
    import { UserController } from './user'
    const routes = Router()
     const controller: UserController = container.get<UserController>(TYPES.UserController)
    routes.get('/users', controller.getUsers)
    //'/users', controller.Create)
    // router.get('/users/:id', controller.FindOne)
    // router.put('/users/:id', controller.Update)
    // router.delete('/users/:id', controller.Delete)
    export { routes }

    Created a /di/index.ts

    import { TYPES } from '../constant/types'
    import { Container } from 'inversify'
    import { UserController }  from '../controller/user'
    import { UserService, IUserService } from '../service/user'
    import { MongoDBClient } from '../utils/mongodb/client'
    let container = new Container()
    export { container }

    Modified the /service/user.ts

    import { inject, injectable } from 'inversify';
    import { MongoDBClient } from '../utils/mongodb/client';
    import { User } from '../models/user';
    import { TYPES } from '../constant/types';
    import { publishToQueue } from '../queueevents/mqpublishingservice'
    export  interface IUserService {
      newUser: (user: User) => Promise<User>
      getUsers: () => Promise< User[]>
      getUser: (id: string) => Promise<User>
      updateUser: (id: string, user: User)=> Promise<User>
      deleteUser: (id: string) => Promise<any>
    export class UserService implements IUserService{
      private mongoClient: MongoDBClient;
        @inject(TYPES.MongoDBClient) mongoClient: MongoDBClient
      ) {
        //console.log(`UserService:constructor: ${JSON.stringify(mongoClient)}`)
        this.mongoClient = mongoClient;
      public getUsers(): Promise<User[]> {
        return new Promise<User[]>((resolve, reject) => {
          this.mongoClient.find('user', {}, (error, data: User[]) => {

    And finally changed the bootstrap.ts to

    import 'reflect-metadata'
    import './di'
    import * as express from 'express'
    import * as cors from 'cors'
    import { routes} from './controller/router'
    const app = express()
    app.use(express.json()) // Recognize the incoming Request Object as a JSON Object
    app.use(express.urlencoded({ extended: true })) //  Recognize the incoming Request Object as strings or arrays
    app.use(cors()) // Enable All CORS Requests
    console.log('Server started on port 3001 :)')
    exports = module.exports = app;

    But I get the error

    TypeError: Cannot read property 'userService' of undefined
    at UserController.getUsers (\MongoDB\controller\user.ts:23:17)

    Which is at (/controller/user.ts)
    return this.userService.getUsers()

    Do not know if somebody already solved it ... I am new to this environment... Thank you

    inversify-express-utils does not support 404 error pages?
      server.setConfig(app => {
        app.use((_, res) => {
    ^When I add this all routes throws out an 404
    Opened issue at inversify/InversifyJS#1231
    Luiz Guilherme D'Abruzzo Pereira
    Hi everyone, I want to know from you how you organize your project using inversify to scale code wise. I have a project using inversify that we register a lot of dependencies and in a integration test we are using the same container that we use for running the application and every time we need to load the container it takes some time because it is loading all the files in the code base. I thought about breaking the application into multiple modules and load them for each test, but then I would have to know which dependencies are in which modules to load all required modules for that test. So I want to see if some of you have experience and dealt with this problem before
    hi, what is a good way to inject parameters for interface member function?
    export interface A {
        play(): void;
    export class CA implements A {
        play() {
            console.log("i am A")
    export interface B {
        adopt(a: A): void; 
    export class CB1 implements B {
        private aa: A[] = [];
        adopt(a: A) { // can inject A here ??? with code in B as it is?
        getA(): A {
            return this.aa[0]
    const cb1 = new CB1()
    cb1.adopt(new CA())
    any advice about the above?? thanks very much
    Ringo De Smet
    I would like to use IoC to behave as a plugin system: in a certain project network, I would use inversify and have some interfaces defined. The dependencies in network/package.json would refer to packages providing the implementation (injectables) for some or all of the interfaces in network. Each of these packages would have their injectables listed via config in package.json.
    Is there already code (or an inversify extension) available that would wire everything based on this information?
    Pattabi M
    I posted a inversify/InversifyJS#1237 on inversify project. It is my understanding that the 'onActivation' can only be applied on a concrete class. I tried on an abstract class, it errored and I also tried on a binding toService, the method is not available. if the understanding is correct, how a cross-cutting concern spanning multiple classes be implemented?
    I looked at tracer and it iterates through the bindings of a container for its functionality.