Search code examples
javascriptdependency-injectioninversion-of-controlnestjsinversifyjs

Inject specific values into object constructor


I have several implementations of an interface and they each need their own configuration injecting into the constructor. My question is if I can somehow hook the dependency injection system in NestJS (presumably Inversify) to inject not just a configuration object, but a specific subset of the configuration object. For example, if config.ts looks like this:

const config = {
    http: {
        host: '0.0.0.0',
        port: 3000,
    },
    adapters: {
        disk: {
            path: 'C:\\path\\to\\my\\stuff',
        },
        dropbox: {
            api_key: 'asdfghjkl;',
            api_secret: 'blahblahblahblahblah'
        }
    },
};

I want to inject the config in such a way that my disk implementation receives config.adapters.disk, my dropbox implementation receives config.adapters.dropbox etc. not just config


Solution

  • if i well understand your request you can use the provider with useValue or useFactory depending what you have to resolve before to be injected. I let you take a look on that part of the documentation.

    As example you can do { token: ‘myToken’, useValue: config.property }

    And then You just have to inject ‘myToken’ into your constructor.

    Also useFactory allow you to process something before returning the value