在Aurelia中按类型从容器中请求类型?

时间:2016-08-02 00:51:52

标签: typescript aurelia

在Java with Spring中,如果我想让一个实例知道可以处理它的东西,我会写这样的东西

interface Executable<T extends Executor> {
   Class<T> executorClass();
}

Executable instance = () -> MyExecutor.class;
Class<T> execClazz = instance.executorClass();
T executor = context.getBean( execClazz );
Results r = executor.execute( instance );

我可以将此模式与Aurelia和Typescript一起使用吗?如果是这样,我如何在Typescript中executorClass定义返回类型(我不知道它们用于Class或如何简单地返回它)。我如何从Aurelia的容器中获得类型?

1 个答案:

答案 0 :(得分:6)

您可以使用get方法从容器中请求类型的实例:

class Foo {
}

let foo = container.get(Foo); // returns an instance of Foo.

在TypeScript中,您可能希望转换get方法的结果:

class Foo {
}

let foo = <Foo>container.get(Foo); // returns an instance of Foo.

如果您有多种类型实现特定接口,请在app startup注册相应的实现:

// interface
class FooService {
  getFoos(): Promise<Foo[]> {
    throw new Error('not implemented'); 
  }
}

class HttpFooService {
  getFoos(): Promise<Foo[]> {
    return fetch('https://api.evilcorp.com/foos')
      .then(response => response.json());
  }
}

class MockFooService {
  getFoos(): Promise<Foo[]> {
    return Promise.resolve([new Foo()]);
  }
}

// app startup... configure the container...
if (TEST) {
  container.registerHandler(FooService, c => c.get(MockFooService));
  // or: container.registerInstance(FooService, new MockFooService());
} else {
  container.registerHandler(FooService, c => c.get(HttpFooService));
  // or: container.registerInstance(FooService, new HttpFooService());
}

// now when you @inject(Foo) or container.get(Foo) you'll get an instance of MockFooService or HttpFooService, depending on what you registered.
let foo = container.get(Foo); // returns an instance of MockFooService/HttpFooService.

我不确定这是否完全回答了你的问题。我从来没有使用过Spring,也没有做过任何Java编程。我没有完全遵循你的问题中的代码。 Here's a link对几个可能有用的容器/ DI用例。{3}}这是另一个可能有帮助的stackoverflow answer。以下是Aurelia DI docs

作为旁注,尽可能远离container.get。使用它违反了依赖性倒置原则。最好列出您的依赖项,而不是主动检索它们:

好(ES6):

@inject(Foo, Bar)
class Baz {
  constructor(foo, bar) {
  }
}

好(TypeScript):

@autoinject
class Baz {
  constructor(foo: Foo, bar: Bar) {
  }
}

不太好:

class Baz {
  constructor() {
    let foo = container.get(Foo);
    let bar = container.get(Bar);
  }
}