Static Inject vs @inject In Aurelia

Last updated: March 16, 2017

A few people have actually asked me this question, so I thought a helpful blog post for reference would finally answer the question: What’s the difference between static inject and @inject in Aurelia?

The answer will surprise you. Okay, not really. It’s a pretty clear-cut answer. There is no difference between either.

Back in the early days of Aurelia before support for decorators was added (we are talking early 2015 here), you did things a little more verbosely because support for decorators was non-existent.

Once upon a time to inject dependencies into a class, you could only do this:

import {EventAggregator} from 'aurelia-event-aggregator';

export class MyVm {
    static inject = [EventAggregator];

    constructor(ea) {
        this.ea = ea;
    }
}

Then a decorator in the form of @inject was added and you could inject like this:

import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class MyVm {
    constructor(ea) {
        this.ea = ea;
    }
}

But behind the scenes, the @inject decorator is setting the inject property on the class anyway. So injecting dependencies still works the same way it always did, you just have a decorator that does this for you.

I probably use @inject 90% of the time, I use TypeScript so that’s @autoinject in most cases for me. Lately, I’ve had an awakening, it’s actually more work to import the @inject decorator and use it than it is to just define dependencies statically.

I’ve noticed some of the official Aurelia libraries also use the static injection approach. Who knows maybe the lack of decorators is a good thing from a build perspective, less to process perhaps?

In future, I will most likely use the static inject method because anything that means I spend less time typing is a good thing. Although, with IDE’s like Visual Studio Code have autocomplete the typing isn’t really an issue.

Purchase Aurelia for Real World Applications over at Leanpub now

 

Dwayne

 

One thought on “Static Inject vs @inject In Aurelia

Leave a Reply

Your email address will not be published. Required fields are marked *