Access instance from other Service Provider


#1

Hi Guys, I have a question to ask about IOC. For this question assumes this is my app.js looks like:

const providers = [
‘example/providers/AProvider’, // has namespaces: Example/A/A1, Example/A/A2
‘example/providers/BProvider’, // has namespaces: Example/B/B1, Example/B/B2
‘example/providers/CProvider’, // Example/C/C1 Depends on Example/A/A1
];

When I started it, it gave me “Cannot find module” error. So the question is what would the right way to do this?

Note:

  • I already read doc about adonis/fold must be dev dependencies, so no mistake there
  • Package registered installed via npm

#2

have you already certified if you are loading your providers correctly?

Following the docs, if your provider isn’t an NPM Package, you must specify its directory, like this:

const providers = [
  path.join(__dirname, '..', 'example/providers', 'AProvider')
  path.join(__dirname, '..', 'example/providers', 'BProvider')
  path.join(__dirname, '..', 'example/providers', 'CProvider')
]

The code above says to AdonisJS to load providers from the appRoot() + example/providers/AProvider or BProvider or CProvider Directory.


#3

Yes, providers already loaded and I able to use all namespace registered in the app. However when CProvider’s class/instance (ex. C1) tried to ioc.use/use Example/A/A1 or Example/A/B1, raise “Cannot find module”.

So to be clear, if my providers not accessing each other, no error. however if one of my provider tried to access other namespaces, raise error.