2016-03-08 54 views
1

喜一鏢單有這個單例類:注入與angular2

class Singleton { 
    static final Singleton _singleton = new Singleton._internal(); 

    factory Singleton() { 
    return _singleton; 
    } 

    Singleton._internal(); 
} 

我想用這種方式來注入我的類中的日誌記錄器:

class Singleton { 
    static final Singleton _singleton = new Singleton._internal(); 

    factory Singleton(@Inject(LoggerService) this.log) { 
    return _singleton; 
    } 

    Singleton._internal(); 
} 

,但似乎該工廠沒有按」不支持注射。

+1

聽起來像Angular2? –

回答

2

在我看來,這是Angular中的錯誤方法。 Angular DI自己提供單身。

class Singleton { 
    final LoggerService log; 

    Singleton(this.log); 
} 
bootstrap(AppComponent, [LoggerService, Singleton]); 

應該做你想要什麼。只要您不向其他地方的供應商添加Singleton(例如在組件上),Angular2將始終注入相同的實例。

如果你仍想保留上面的圖案,使用

bootstrap(AppComponent, [ 
    LoggerService, 
    provide(Singleton, 
     useFactory: (log) => new Singleton(log), 
     deps: [LoggerService]) 
]); 
+1

完美@Günter。它更適合這種模式:) –