by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Thomas Chiantia
    @TomzBench
    But container makes easier to create dependency
    Alex
    @AlexHladin
    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
    @joelday
    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
    @TomzBench
    @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";
    jest.mock("./place");
    
    const mockDependency!: MockDependency // (!) not real dependency
    const uutDependency = new Thing (mockDependency);
    const uut = new Uut(uutDependency);
    
    // ...
    
    expect(uutDependency).toHaveBeenCalledWith(...
    Alex
    @AlexHladin
    @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)
    
      a.someMethodThatUseDependency();
    
      expect(dependency.someFunction).toHaveBeenNthCalledWith(1, ....);
    })
    @joelday could you provide some examples?
    Thomas Chiantia
    @TomzBench
    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. (https://github.com/inversify/InversifyJS/blob/master/wiki/good_practices.md) ...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...
    grimmersnee
    @grimmersnee
    Hey guys, quick question regarding https://github.com/inversify/inversify-express-utils#authprovider. 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
    @ccravens

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

    container = new Container();
    container
          .bind<MyService>(SERVICES.MyService)
          .to(MyServiceImpl);

    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
      }
    }
    alikarimii
    @alikarimii
    @sanex3339 Are you figure it out?

    @sanex3339

    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) {...
            this.bar = 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
    @vitekob249_gitlab
    Hello everyone
    Could anyone help with provide and injectLazy decorators in inversify typescript project please?
    Here's StackOverflow question
    https://stackoverflow.com/questions/61556606/inversifyjs-binding-decorators-and-lazy-inject
    Thanks!
    George Tsomlektsis
    @UltraWelfare
    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

    @injectable()
    export abstract class Command implements ICommand {
        commandName!: string
        subcommands: ICommand[] = []
        @inject(TYPES.MessageListenerLogger) logger!: pino.Logger
    
        public async execute(message: Message, args: string[]) {
                  ''code''
        }
    
        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 :

    DIContainer.bind<ICommand>(TYPES.Command)
        .to(SubcommandCreate)
        .whenTargetNamed("CommandTournament")
    
    DIContainer.bind<ICommand>(TYPES.Command)
        .to(SubcommandList)
        .whenTargetNamed("CommandTournament")

    And the CommandTournament constructor is:

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

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

    alikarimii
    @alikarimii
    @UltraWelfare .whenTargetNamed("CommandTournament") is the same in both
    George Tsomlektsis
    @UltraWelfare
    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 ?
    alikarimii
    @alikarimii
    .whenTargetNamed("SubcommandCreate")
    .whenTargetNamed("SubcommandList")
    test this
    George Tsomlektsis
    @UltraWelfare
    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
    @AiusDa
    Someone knows how can I apply an Inyection like angular? example:
    constructor(private someService:  SomeService)
    Alex
    @AlexHladin
    @AiusDa just add @inject(TYPES...) annotation
    Kamil Solecki
    @Kamilczak020
    Hello
    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
    @Kamilczak020
    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
    @Kamilczak020
    nvm, it already is in issues: inversify/InversifyJS#1079
    Dominic Robinson
    @dcrdev
    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.
    bertellig
    @bertellig

    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';
    
    @injectable()
    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)
    // router.post('/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()
    container.bind<MongoDBClient>(TYPES.MongoDBClient).to(MongoDBClient)
    container.bind<IUserService>(TYPES.IUserService).to(UserService)
    container.bind<UserController>(TYPES.UserController).to(UserController)
    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>
    }
    @injectable()
    export class UserService implements IUserService{
      private mongoClient: MongoDBClient;
      constructor(
        @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[]) => {
            resolve(data);
          });
        });
      }

    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
    app.use(routes);
    app.listen(3001);
    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

    Alfon
    @alfonmga
    inversify-express-utils does not support 404 error pages?
      server.setConfig(app => {
        app.use((_, res) => {
          res.sendStatus(400)
        })
      })
    ^When I add this all routes throws out an 404
    Alfon
    @alfonmga
    Opened issue at inversify/InversifyJS#1231
    Luiz Guilherme D'Abruzzo Pereira
    @luiz290788
    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
    DavidXiao
    @davidxiao
    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?
            this.aa.push(a)
        }
        getA(): A {
            return this.aa[0]
        }
    }
    
    const cb1 = new CB1()
    cb1.adopt(new CA())
    cb1.getA().play()
    DavidXiao
    @davidxiao
    any advice about the above?? thanks very much
    Ringo De Smet
    @ringods
    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
    @patb23in_twitter
    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.