Injecting dependencies into your classes is straightforward in Aurelia. Aurelia provides multiple mechanisms to declare and manage dependencies, ensuring that each class receives the necessary instances it requires.
Declaring Dependencies with @inject
The @inject decorator is the primary method for declaring a class's dependencies. It specifies which dependencies should be injected into the class upon instantiation.
TypeScript offers an experimental feature to provide type metadata to Aurelia's DI container automatically. By enabling "emitDecoratorMetadata": true in your tsconfig.json, you can use the @autoinject decorator to eliminate the need to specify dependencies manually.
Interestingly, you don't need to use Aurelia's @autoinject decorator at all to achieve this. Adding any decorator will trigger TypeScript to emit type metadata. However, using @autoinject enhances code clarity and consistency.
Providing Inject Metadata without Decorators
If you're not using Babel's or TypeScript's decorator support or prefer not to, you can provide inject metadata using a static inject property or method on your class.
Static inject Property: Assign an array of dependencies to the static inject property of the class.
Order Matters: Ensure that the order of dependencies in the inject array matches the constructor parameters.
No Decorators Needed: This method provides flexibility for environments where decorators are not preferred or supported.
Recursive Dependency Resolution
Aurelia's DI container resolves dependencies recursively. If class A depends on class B, and class B depends on classes C and D, the container will resolve all dependencies in the hierarchy automatically.