# Dependency Injection
# Introduction
ExpressWebJs service container is used to resolve all ExpressWebJs controllers. As a result, you are able to type-hint any dependencies you've registered in the App/Providers/AppServiceProvider.ts register method into your controller constructor. The declared dependencies will automatically be resolved and injected into the controller instance:
First register your service in App/Providers/AppServiceProvider.ts register method:
import ServiceProvider from "Elucidate/Support/ServiceProvider";
import { MyService } from "App/Service/MyService";
export class MyServiceProvider extends ServiceProvider {
/**
* Register application services.
* @return void
*/
register() {
this.singleton(MyService);
}
}
We can now inject MyService into our UserController constructor:
import { MyService } from "App/Service/MyService";
export class UserController {
constructor(private myService: MyService) {}
}
# Autowire
Starting with Version 4.1, ExpressWebJs introduced Autowire feature which enables you to inject an object dependency implicitly. It internally uses setter or constructor injection.
ExpressWebJs Autowire feature automatically resolves an object registered in your service provider. This is handy for property injection. Autowire can't be used to inject primitive and string values.
Let's create a spell checker class and register it in our service provider:
export class SpellChecker {
public async checkSpelling(): Promise<void> {
console.log("Inside checkSpelling.");
}
}
# Register SpellChecker
class to APPServiceProvider register method.
import ServiceProvider from "Elucidate/Support/ServiceProvider";
import { TextEditor } from "App/Service/TextEditor";
import { SpellChecker } from "App/Service/SpellChecker";
export class AppServiceProvider extends ServiceProvider {
/**
* Register any application services.
* @return void
*/
public register() {
this.singleton(TextEditor);
this.singleton(SpellChecker); 👈 spellchecker service
}
}
# Autowire Class
Let's Autowire SpellChecker
class into TextEditor class
import { SpellChecker } from "./SpellChecker";
export class TextEditor {
private spellChecker = Autowire(SpellChecker); 👈 spellchecker service auto wired
public getSpellChecker(): SpellChecker {
return spellChecker;
}
public spellCheck(): void {
spellChecker.checkSpelling();
}
}