A dependency injection container is a tool that can simplify the process of decomposing such a system. Often times, when developers go through the work of destructuring a system, they introduce a new complexity of "re-assembling
" the smaller parts again at runtime. This is what a dependency injection container can do for you, using simple declarative hints.
Injection : Let's say we have a CustomerEditScreen
that needs to load a Customer
entity by ID from a web service
. We wouldn't want to place all the details of our AJAX implementation inside our CustomerEditScreen
class. Instead, we would want to factor that into a CustomerService
class that our CustomerEditScreen
, or any other class, can use when it needs to load a Customer
. Aurelia's dependency injection container lets you accomplish this by declaring that the CustomerEditScreen
needs to have a CustomerService injected
at creation time.
CustomerEditScreen Injection : TypeScript
import {CustomerService} from 'backend/customer-service';
import {inject} from 'aurelia-framework';
@inject(CustomerService)
export class CustomerEditScreen {
constructor(private customerService: CustomerService) {
this.customer = null;
}
activate(params) {
return this.customerService.getCustomerById(params.customerId)
.then(customer => this.customer = customer);
}
}