注入实现某个接口的所有服务 [英] Inject all Services that implement some Interface

查看:24
本文介绍了注入实现某个接口的所有服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单场景:

我有多个实现通用接口的服务.所有这些服务都在 bootstrap 方法中注册.

I have multiple Services that implement a common Interface. All those Services are registered within the bootstrap method.

现在我想要另一个服务,它注入所有实现公共接口的注册服务.

Now I'd like to have another Service, which injects all registered Services that implement the common Interface.

export interface MyInterface {
    foo(): void;
}

export class Service1 implements MyInterface {
    foo() { console.out("bar"); }
}

export class Service2 implements MyInterface {
    foo() { console.out("baz"); }
}

export class CollectorService {
    constructor(services:MyInterface[]) {
        services.forEach(s => s.foo());
    }
}

这有可能吗?

推荐答案

您需要像这样注册您的服务提供商:

You need to register your service providers like this:

boostrap(AppComponent, [
  provide(MyInterface, { useClass: Service1, multi:true });
  provide(MyInterface, { useClass: Service2, multi:true });
]);

这仅适用于没有接口的类,因为接口在运行时不存在.

This will work only with classes not with interfaces since interfaces don't exist at runtime.

要使其与接口一起工作,您需要对其进行调整:

To make it work with interfaces, you need to adapt it:

bootstrap(AppComponent, [
  provide('MyInterface', { useClass: Service1, multi:true }),
  provide('MyInterface', { useClass: Service2, multi:true }),
  CollectorService
]);

并以这种方式注入:

@Injectable()
export class CollectorService {
  constructor(@Inject('MyInterface') services:MyInterface[]) {
    services.forEach(s => s.foo());
  }
}

有关更多详细信息,请参阅此 plunkr:https://plnkr.co/edit/HSqOEN?p=预览.

See this plunkr for more details: https://plnkr.co/edit/HSqOEN?p=preview.

查看此链接了解更多详情:

See this link for more details:

这篇关于注入实现某个接口的所有服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆