Dependency Injection Constructor that takes arguments

有些话、适合烂在心里 提交于 2019-12-24 10:32:13

问题


I'm building an Aurelia app that uses "Models" for every type of data object.

All my Models look something like this:

export class Item {
    id = null;
    name = '';
    description = '';

    constructor (data) {
        Object.assign(this, data);
    }
}

And I later create objects like this:

export class SomeViewModel {
    activate () {
        this.myItem = new Item({
            name: 'My Item!', 
            description: 'This is my item. It will be initialized with these properties.'
        });
    }
}

I got the Object.assign() bit from an article I read and it works really well. It allows me to create new items using data from the server, or if I want an empty Item I simply don't pass in anything.

Now I've reached a point where I need my model to have access to another class so I'm using Aurelia's Dependency Injection like this:

import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';

@inject(Router)
export class Item {
    id = null;
    name = '';
    description = '';

    constructor (router, data) {
        this.router = router;
        Object.assign(this, data);
    }

    get permalink () {
        return window.location.protocol + '//' + window.location.host + this.router.generate('item', {itemId: this.id});
    }
}

Now my problem is this; how do I create a new Item() without passing in the Router myself? I guess switching the order of argument to constructor() would do the trick but that doesn't seem to work with Aurelia?

And I don't want to have to do this every time I create a new Item:

import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';

@inject(Router)
export class SomeViewModel {
    constructor (router) {
        this.router = router;
    }

    activate () {
        this.myItem = new Item(this.router, {
            name: 'My Item!', 
            description: 'This is my item. It will be initialized with these properties.'
        });
    }
}

Surely there must be a better way to solve this?


回答1:


Use the Factory resolver. Here's an example: https://gist.run?id=46642ac54893186067e7cd890d6722a3**

import {inject, Factory} from 'aurelia-dependency-injection';
import {MyModel} from './my-model';

@inject(Factory.of(MyModel))
export class App {
  message = 'Hello World!';

  constructor(createModel) {
    let model = createModel('my data');
  }
}

my-model.js

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

@inject(EventAggregator)
export class MyModel {
  constructor(eventAggregator, data) {
    console.log(eventAggregator, data);
  }
}


来源:https://stackoverflow.com/questions/39038583/dependency-injection-constructor-that-takes-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!