Injection
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
@injectThe @inject decorator is the primary method for declaring a class's dependencies. It specifies which dependencies should be injected into the class upon instantiation.
Example:
import { CustomerService } from 'backend/customer-service';
import { inject } from 'aurelia-framework';
@inject(CustomerService)
export class CustomerEditScreen {
constructor(customerService) {
this.customerService = customerService;
this.customer = null;
}
activate(params) {
return this.customerService.getCustomerById(params.customerId)
.then(customer => this.customer = customer);
}
}Key Points:
Decorator Usage: The
@injectdecorator lists the dependencies required by the class.Constructor Matching: The constructor parameters should match the dependencies declared in the
@injectdecorator, both in type and order.Multiple Dependencies: You can inject multiple dependencies by listing them within the
@injectdecorator.
Example with Multiple Dependencies:
Using @autoinject with TypeScript
@autoinject with TypeScriptTypeScript 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.
Example:
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.
Example:
Key Points:
Static
injectProperty: Assign an array of dependencies to the staticinjectproperty of the class.Order Matters: Ensure that the order of dependencies in the
injectarray 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.
Example:
When ServiceA is instantiated, Aurelia automatically resolves ServiceB, which in turn resolves ServiceC and ServiceD.
Last updated
Was this helpful?