簡體   English   中英

將 IConfigurationSection 轉換為 IOptions

[英]Converting IConfigurationSection to IOptions

選項模式允許我創建包含配置值的選項對象,如下所述: https : //docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options

我需要 IDesignTimeDbContextFactory 實現中一個選項對象的值,以便 EF 在創建模型時使用。 (該配置部分中的值將用於數據播種,因此我將 IOptions 添加到 DB Context 構造函數。)

由於我無法訪問 IServiceCollection(因為它是設計時間 - 就像運行“dotnet ef migrations add”時一樣,我需要有另一種方法將 IConfigurationSection(代表我感興趣的部分)轉換為我的自定義選項類。

我可以知道如何在沒有依賴注入的情況下做到這一點嗎?

您可以使用Bind(Configuration, object)擴展方法來執行任何object手動綁定。 下面是一個例子:

var myCustomOptions = new MyCustomOptions();
myConfigurationSection.Bind(myCustomOptions);

// Use myCustomOptions directly.

要將其包裝在IOptions<T> ,請使用Options.Create

IOptions<MyCustomOptions> myOptions = Options.Create(myCustomOptions);

我猜你需要Bind方法:

var config = new ConfigurationBuilder()...Build();
var myOptions = new MyOptions();
config.GetSection("MyOptions").Bind(myOptions);

你也可以使用

config.Get<MyCustomOptions>()

這是來自 Microsoft.Extensions.Configuration 命名空間的擴展方法。 我在 Assembly Microsoft.Extensions.Configuration.Binder, Version=3.1.9.0 中看到它。 也許,它也存在於早期版本中。 這會給你設置對象本身。 然后你可以將它包裝到 IOptions 中,就像 Krik 在另一個答案中展示的那樣。

ServiceCollectionContainerBuilderExtensions使這個工作在 SoapCore 中

我的應用程序中的部分是這樣的:

            services.AddSingleton<IRESAdapterService>(new RESAdapterService(
                new XController(
                    services.BuildServiceProvider().GetRequiredService<IOptions<XApiSettingsFromJsonClass>>(),
                    _xLogger
                    )));

也可用於完整性單元測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM