How to get instance of a injected Service
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) .
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 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 .
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
Amazing , that is exactly what i wanted.!!!