我想将单例范围限定到路由,以便每次用户重新输入路由时都会创建一个新实例。我以为可以在路由视图模型的(自动创建的)子容器中注册实例,但出现错误:
错误[应用路由器] ReferenceError:初始化前无法访问'SomeOtherClass'
如何在路由的容器中注册单例,使其仅作用于该路由?
我的路由虚拟机看起来像
import {autoinject, Container} from 'aurelia-framework';
import {SomeOtherClass} from '...some-other-class'; // The actual relative path
@autoinject
export class SomeRoute {
constructor(private container: Container) {
container.registerInstance(SomeOtherClass);
}
}
我要注册的类会自动注入到路由内的各个组件中。该类看起来像
import {autoinject} from 'aurelia-framework';
@autoinject
export class SomeOtherClass {
constructor(private dep1: Dep1, private dep2: Dep2) {
// Stuff that I want to re-run every time the user (re)enters the route
}
}
和其他类只是像这样注入它
import {autoinject} from 'aurelia-framework';
import {SomeOtherClass} from '...some-other-class'; // The actual relative path
@autoinject
export class SomeComponent {
constructor(someOtherClass: SomeOtherClass) {
// Use the singleton instance within this route
}
}
B,我发现了问题!错误消息对我有些误导。
问题是Foo
正在导入视图模型类(因为我在其上粘贴了公共静态常量)。该视图模型类尚未由路由器初始化。我将常量移到了另一个类上(无论如何也确实不属于那个类),错误消失了。
我还确认了Foo
的单例现在已限制到该路线的子容器。