[英]Register multiple instances of IHostedService with different constructor parameters (DI and non-DI) in .NET Core
[英]Constructor with non-DI and DI parameters
我正在創建需要一些配置參數和記錄器的服務。 這是我的服務的構造函數:
public StorageProvider(string directory, ILogger<StorageProvider> logger)
我剛剛添加了記錄器。 我以前在我的startup.cs中像這樣初始化它:
services.AddSingleton<IStorageProvider>(
new StorageProvider(Configuration["TempStorage.Path"]));
directory
參數來自配置文件,記錄器進行DI處理。 如何設置IStorageProvider
?
您應該執行以下操作:
TempStorage:Path
包裝到其自己的配置類中,例如StorageProviderSettings
。 StorageProvider
依賴於該新配置類。 例:
public sealed class StorageProviderSettings
{
public readonly string TempStoragePath;
public StorageProviderSettings(string tempStoragePath)
{
if (string.IsNullOrWhiteSpace(tempStoragePath))
throw new ArgumentException(nameof(tempStoragePath));
this.TempStoragePath = tempStoragePath;
}
}
public sealed class StorageProvider : IStorageProvider
{
public StorageProvider(
StorageProviderSettings settings, ILogger<StorageProvider> logger)
{
// ...
}
}
// Registration
services.AddSingleton(new StorageProviderSettings(Configuration["TempStorage.Path"]));
services.AddSingleton<IStorageProvider, StorageProvider>();
使用Tratcher在注釋中建議的“ Options
模式。 在Configuration的官方文檔中了解更多信息。
基本上,您定義一個類來保存所需的值:
public class StorageProviderOptions
{
public string TempStoragePath { get; set; }
}
然后在ConfigureServices
注冊類型:
services.Configure<StorageProviderOptions>();
在代碼中,您請求IOptions<StorageProviderOptions>
並將其設置為StorageProviderOptions
的實例:
public class SomeController
{
private readonly StorageProviderOptions _options;
public SomeController(IOptions<StorageProviderOptions> options)
{
_options = options.Value;
}
}
最后,請確保您的配置源中有一個與TempStoragePath
名稱匹配的TempStoragePath
。 或者,您可以使用以下代碼在ConfigureServices
注冊該選項:
services.Configure<ServiceProviderOptions>(o => o.TempStoragePath = "temp");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.