Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia dependency injection when instantiating objects

If I create a supporting class, e.g. UserList that has HttpClient injected it into it, then whoever instantiates that class will have to pass an HttpClient object to it in the constructor. Shouldn't the @inject(HttpClient) take care of getting the HttpClient singleton and injecting it into the constructor? Otherwise every class that needs to refererence UserList will also have get a reference to HttpClient so that it can then pass it to the UserList constructor (and defeating the purpose of injection).

UserList.ts

@inject(HttpClient)
export class UserList {
    constructor(public http: HttpClient){
    }
...
}

DoSomething.ts

export class DoSomething {
    userList: UserList;

    constructor(){
         this.userList = new UserList(); //doesn't work without passing HttpClient
    }
}

to make this work I have to get a reference to HttpClient in the DoSomething class even though it won't be using it directly. The working version which seems to be poorly implemented:

DoSomething.ts

@inject(HttpClient)
export class DoSomething {
    userList: UserList;

    constructor(public http: HttpClient){
         this.userList = new UserList(http); 
    }
}
like image 639
user441058 Avatar asked Nov 29 '22 09:11

user441058


1 Answers

If you use typescript, don't worry about this. Use @autoinject and see magic happen!

Like this:

import {autoinject} from 'aurelia-framework';

@autoinject()
export class UserList {
    constructor(private http: HttpClient){
    }
...
}

In other file:

import {autoinject} from 'aurelia-framework';

@autoinject()
export class DoSomething {
    constructor(private userList: UserList){
    }
}

The TypeScript compiler will emit the type metadata and Aurelia will read this injecting instances on correct way!

More information about: http://aurelia.io/docs.html#/aurelia/dependency-injection/1.0.0-beta.1.2.3/doc/article/dependency-injection-basics

like image 102
Abraão Alves Avatar answered Dec 05 '22 11:12

Abraão Alves