我有這樣的問題 - 我有一個單身'設置'服務,我想使用。我解決了它的真正創建一個,然後通過讓你指定一個「供應商」,而不是僅僅註冊類,並添加一個漂亮的大註釋解釋這個超載登記,準確的實例與DI:
var settingsService = new SettingsService(_hostingEnvironment);
//Add a concrete settings service which is then registered as the de facto settings service for all time.
//we need to do this as we want to use the settings in this method, and there isn't a satisfactory method to
//pull it back out of the IServiceCollection here (we could build a provider, but then that's not the same provider
//as would be build later... at least this way I have the exact class I'll be using.
services.AddSingleton<ISettingsService, SettingsService>((p) => settingsService);
..
..
..
var thing = settingsService.SomeSettingIWant();
如果你想要的不是單身,而是暫時的,那麼我想你可以在那裏爲它創建一個具體的類。我知道它可能有點像作弊,但它會正常工作...
來源
2017-10-19 11:53:53
GPW
你爲什麼要這樣做?你想達到什麼目的? –
這似乎是[XY問題](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。你試圖達到的最終目標是什麼? – Nkosi