How to inject services in AdonisJs V5 - Constructor, Method
serjo agro
Posted on August 2, 2021
In this post i will give you 2 examples for injection of services to adonisjs v5 constructors, and methods
create new provider: MyServiceProvider.ts
import { ApplicationContract } from '@ioc:Adonis/Core/Application'
import {MyServiceImp} from "Providers/MyServiceImp";
export default class MyServiceProvider {
public static needsApplication = true
constructor (protected application: ApplicationContract) {
console.log('i was called');
}
public register () {
this.application.container.bind('@ioc:MyNameSpace/MyService', () => {
console.log('@ioc:MyNameSpace/MyService');
return new MyServiceImp('http');
});
this.application.container.bind('MyNameSpace/MyService', () => {
console.log('MyNameSpace/MyService');
return new MyServiceImp('https');
});
}
public async boot () {
// All bindings are ready, feel free to use them
console.log('ready');
}
public async ready () {
// App is ready
}
public async shutdown () {
// Cleanup, since app is going down
}
}
create new interface: MyServiceContract.ts
declare module '@ioc:MyNameSpace/MyService' {
export interface MyServiceContract {
protocol?: string;
}
}
create new interface implementation: MyServiceImp.ts
import {MyServiceContract} from "@ioc:MyNameSpace/MyService";
export class MyServiceImp implements MyServiceContract {
protocol: string;
constructor(protocol: string) {
this.protocol = protocol;
}
}
add to file adonisrc.json in providers array:
"./providers/MyServiceProvider"
usage:
iam giving here 2 namespacing examples, you can choose how ever you prefer
add to controller/service - what ever you need
import {inject} from "@adonisjs/fold";
import {MyServiceContract} from "@ioc:MyNameSpace/MyService";
// constructor injection, pay attention to array indexes
// this will log from service provider register method
// console.log('@ioc:MyNameSpace/MyService'); - for example
@inject(['@ioc:MyNameSpace/MyService', 'MyNameSpace/MyService'])
export default class MyController {
constructor(protected service1: MyServiceContract, protected service2: MyServiceContract) {
console.log(service1, service2);
}
// option 2 - method injection
// same here, 2 example of getting service from ioc by namespace
@inject([null, '@ioc:MyNameSpace/MyService', 'MyNameSpace/MyService'])
public async index({inertia, request}: HttpContextContract, myService: MyServiceContract, myService2: MyServiceContract) {
console.log(myService, myService2);
}
}
💖 💪 🙅 🚩
serjo agro
Posted on August 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
githubcopilot AI Innovations at Microsoft Ignite 2024 What You Need to Know (Part 2)
November 29, 2024