InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

How to get instance of a injected Service

Open KumarS-Naveen opened this issue 6 years ago • 4 comments

First of all sorry for asking question here , i did not get any suitable answers to my question hence directly posting it here .

Requirement for me is to get an instance of a injected service in Main.ts file so that i can call a method in class as soon as the server is up .

@Injectable Class A implements IA { @Inject(.. Other Services) methodA(){} }

In the above context is there any way for me to get the instance of class A , instead of creating A a = new A(..Initialize another Service instance and so on) .

KumarS-Naveen avatar Feb 23 '20 16:02 KumarS-Naveen

Hi there! First of all, you have to bind your service to your container.

const container = new Container() // Container from inversify
container.bind(TYPES.MyService).to(MyService) // Where TYPES.MyService is just an identifier for your binding

...

// Retrieving MyService from your container
const MyService = container.get(TYPES.MyService)

...

// Retrieving MyService through dependency injection in another class/service
class MyClass {
  constructor( 
    @inject(TYPES.MyService) private service: Service
  ) {}

  someFunction() {
    // Using your service
    this.service.someCall()
  }
}

Does this answer your question?

vitorfreitas avatar Feb 28 '20 21:02 vitorfreitas

@vitorfreitas Thanks for the answer . Sorry i did not make myself clear at the first go . I wanted to know how to consume the service in Main.ts / Server.ts file (The start up file in Express ) Because there is no constructor in the main file .

KumarS-Naveen avatar Feb 29 '20 15:02 KumarS-Naveen

Got it! I'll show you exactly how I do at my server.ts file, hope it helps!

import { Logger } from 'winston'
import { AddressInfo } from 'net'
import createApp from './app'
import bootstrap from './bootstrap'
import { TYPES } from './utils/ioc-types'

const DEFAULT_PORT = 3000

const PORT = process.env.PORT || DEFAULT_PORT

async function main() {
  const container = await bootstrap()

  const app = await createApp(container)

  const server = app.listen(PORT, () => {
    const addr = server.address() as AddressInfo
    const logger = container.get<Logger>(TYPES.Logger)
    logger.info(`Server listening on ${addr.address}:${addr.port}!`)
  })
}

main()

Where bootstrap.ts is responsible for creating and returning the container with all the bindings

vitorfreitas avatar Mar 01 '20 02:03 vitorfreitas

Amazing , that is exactly what i wanted.!!!

KumarS-Naveen avatar Mar 01 '20 02:03 KumarS-Naveen