Reputation: 1384
Hi have this singleton class:
class Singleton {
static final Singleton _singleton = new Singleton._internal();
factory Singleton() {
return _singleton;
}
Singleton._internal();
}
i want to inject a Logger inside my class in this way:
class Singleton {
static final Singleton _singleton = new Singleton._internal();
factory Singleton( @Inject(LoggerService) this.log) {
return _singleton;
}
Singleton._internal();
}
but it seem that Factory doesn't not support the injection.
Upvotes: 2
Views: 507
Reputation: 658027
In my opinion this is the wrong approach in Angular. Angular DI provides singletons by itself.
class Singleton {
final LoggerService log;
Singleton(this.log);
}
bootstrap(AppComponent, [LoggerService, Singleton]);
should do what you want. As long as you don't add Singleton
to providers elsewhere (for example on a component) Angular2 will always inject the same instance.
If you still want to keep above pattern, use
bootstrap(AppComponent, [
LoggerService,
provide(Singleton,
useFactory: (log) => new Singleton(log),
deps: [LoggerService])
]);
Upvotes: 2