Inject all Services that implement some Interface

℡╲_俬逩灬. 提交于 2019-12-18 04:01:28

问题


Simple scenario:

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.

i.e.

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());
    }
}

Is that possible somehow?


回答1:


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
]);

and inject this way:

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

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

See this link for more details:

  • http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html



回答2:


Because interfaces are not available at runtime (only for static checks) interfaces can't be used as toke for DI.

Use a token instead:

(deprecated) https://angular.io/api/core/OpaqueToken

var myInterfaceToken = new OpaqueToken('MyInterface');

https://angular.io/api/core/InjectionToken

var myInterfaceToken new InjectionToken<MyInterface>('MyInterface');
// import `myInterfaceToken` to make it available in this file

@NgModule({
  providers: [ 
    { provide: myInterfaceToken, useClass: Service1, multi:true },
    { provide: myInterfaceToken, useClass: Service2, multi:true },
  ],
  boostrap: [AppComponent],
)
class AppComponent {}
// import `myInterfaceToken` to make it available in this file

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


来源:https://stackoverflow.com/questions/35916542/inject-all-services-that-implement-some-interface

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