.netコアの設定は、ほとんどの場合、POCOまたはIOptionsの上に構築されています。個々のキーを取得するのではなく、代わりに設定クラスを構築します。以前は、CustomConfigurationクラスを作成するか、AppSettingsの前に「グループ化」する必要がありました。もう違います!あなたがIOptionsを使うというアプローチをとるなら、それは以下のように働きます。
あなたappSettings.jsonは、次のようになります:
{
"myConfiguration": {
"myProperty": true
}
}
あなたは、あなたの設定に一致するPOCOを構成しています。次のようなもの:
public class MyConfiguration
{
public bool MyProperty { get; set; }
}
次に、startup.csで、設定をオプションオブジェクトにロードする必要があります。結局、次のような形になります。
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfiguration>(Configuration.GetSection("myConfiguration"));
}
}
次に、DIはすべてIOptionsオブジェクトを挿入するように設定されています。あなたはそのようにようにコントローラに注入します:
public class ValuesController : Controller
{
private readonly MyConfiguration _myConfiguration;
public ValuesController(IOptions<MyConfiguration> myConfiguration)
{
_myConfiguration = myConfiguration.Value;
}
}
IOptionsオブジェクトを使用し、あなただけのコントローラにPOCOに注入していないこと、これを行うために他の方法があります。 (私を含む)一部の人々は、この方法を好む。あなたはもっとここで読むことができます:http://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/
そしてもちろんの公式ドキュメントのドキュメントのリンクをここにある:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
変換に失敗した値を投稿してください。どのタイプに変換しようとしているのでしょうか。 –