Angular:查找实现特定接口的所有提供者

Pet*_*ser 3 strategy-pattern service-locator angular

在我的Angular(4+)应用程序中,我想创建一个基本的插件机制:

  • 扩展点定义为接口
  • 扩展实现该接口
  • 要查找所有扩展,我需要在运行时发现该接口的实现.

示例:SearchStrategy与实现的接口PersonSearchStrategy和DocumentSearchStrategy(两个服务,注册为提供者).

有没有办法通过查询SearchStrategy接口的实现来动态获取这些服务的实例?怎么样?

(可能是一些与注射器相关的功能?)

Chy*_*bie 6

如果您注册服务InjectionToken并使用提供,则有可能提供multi.

您可以使用接口创建注入令牌.

export const SearchStrategyToken = new InjectionToken<SearchStrategy[]>('SearchStrategy');
Run Code Online (Sandbox Code Playgroud)

在您的模块寄存器中:

providers: [
  {provide: SearchStrategyToken, useClass: PersonSearchStrategy, multi: true}, 
  {provide: SearchStrategyToken, useClass: DocumentSearchStrategy, multi: true},
]
Run Code Online (Sandbox Code Playgroud)

在您的组件或服务中:

constructor(private injector: Injector) {

  const services = this.injector
  .get(SearchStrategyToken); // return 2 items [ PersonSearchStrategy, DocumentSearchStrategy ]

  const personSearch = services.find(x => x.constructor.name === 'PersonSearchStrategy');

  const docSearch = services.find(x => x.constructor.name === 'DocumentSearchStrategy');

}
Run Code Online (Sandbox Code Playgroud)

此处提供的代码示例:https://stackblitz.com/edit/angular-clxr6k.

但是,如果您提供有关用例的更多详细信息,那将是一件好事.可能有比上述路线更好的解决方案.

  • 这基本上就是我做的.我唯一的狡辩是你如何注射它.我会注射令牌而不是注射器.`constructor(@Inject(SearchStrategyToken)searchStrategies:SearchStrategy []){...}` (2认同)