Dependency Injection in Aurelia
Aurelia provides a powerful and straightforward approach to Dependency Injection (DI). DI allows you to write cleaner, more testable code by separating object creation from object usage. With Aurelia, you simply declare what dependencies you need, and the framework takes care of the rest.
Key Points
-
Automatic Resolution: Aurelia uses conventions to automatically resolve constructors. If a class depends on another class, Aurelia’s DI container will create an instance of that class on your behalf.
-
Decorators: You can use decorators (like @inject) to explicitly tell Aurelia how to resolve a dependency.
-
Configuration: You can also configure dependencies manually by registering them with Aurelia’s container, but in most basic scenarios, the framework’s conventions are enough.
Below is a minimal example that demonstrates injecting a service (a simple logger) into a component (the root of the application).
logger.ts:
my-app.ts:
my-app.html:
main.ts:
How it works:
-
The Logger class is a simple service with a log method.
-
In the MyApp class, the @inject(Logger) decorator instructs Aurelia to provide an instance of Logger when MyApp is created.
-
When MyApp is instantiated, Aurelia resolves the Logger dependency automatically. You can then call this.logger.log(...).