[Adonis 4.1] How can i register a Class into IoC ? #1346
-
I have a "Service" class, and need to put it to IOC as a singleton... where do i add it? I tried to add in a Custom Service Provider but nothing happens... "use strict";
const path = require("path");
const { ServiceProvider, ioc } = require("@adonisjs/fold");
class WhatsAppProvider extends ServiceProvider {
/**
* Register namespaces to the IoC container
*
* @method register
*
* @return {void}
*/
register() {
ioc.singleton("WemersonRV/WhatsApp", function (app) {
const WhatsAppService = require(path.join(
__dirname,
"../app/Services/WhatsAppService"
));
console.log("I think it's fine....");
return new WhatsAppService();
});
}
/**
* Attach context getter when all providers have
* been registered
*
* @method boot
*
* @return {void}
*/
boot() {
//
}
}
module.exports = WhatsAppProvider;
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I'm pretty much trying to figure this out as well but seems there isn't much traction with this for one reason or another. |
Beta Was this translation helpful? Give feedback.
-
WOW!!! Understand it now! The code is right. I just missunderstood how it works! I thought it would already start with the application, but it is registered only... and keeps this way until first user request comes in,so the singleton is initialized and, in the next ones, it is reused! Or register the singleton into IoC in ServiceProvider |
Beta Was this translation helpful? Give feedback.
WOW!!! Understand it now!
The code is right. I just missunderstood how it works!
I thought it would already start with the application, but it is registered only... and keeps this way until first user request comes in,so the singleton is initialized and, in the next ones, it is reused!
Or register the singleton into IoC in ServiceProvider
register
method and do the 1st use of it inboot
method of same provider, making it available when app starts... I think this is the best way because let the lib's listeners and handlers working when app starts.