Microsoft.Extensions.Configuration
一、MemoryConfigurationSource
Dictionary<string, string> source = new Dictionary<string, string> { ["longDatePattern"] = "dddd, MMMM d, yyyy", ["longTimePattern"] = "h:mm:ss tt", ["shortDatePattern"] = "M/d/yyyy", ["shortTimePattern"] = "h:mm tt" }; IConfiguration config = new ConfigurationBuilder() .Add(new MemoryConfigurationSource { InitialData = source }) .Build();
二、JsonConfigurationSource
Configuration = new ConfigurationBuilder() //.SetBasePath(Directory.GetCurrentDirectory()) //AppDomain.CurrentDomain.BaseDirectory是程序集基目錄,所以appsettings.json,需要復制一份放在程序集目錄下, .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .Add(new JsonConfigurationSource { Path ="Config\\appsettings.json", ReloadOnChange = true }) //ReloadOnChange = true 當appsettings.json被修改時重新加載 .Add(new JsonConfigurationSource { Path ="Config\\SuperSocket.json", ReloadOnChange = true }) //ReloadOnChange = true 當appsettings.json被修改時重新加載 .Build();
或
var executionFolder = Path.GetDirectoryName(typeof(Program).Assembly.Location); AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext context, AssemblyName assembly) => context.LoadFromAssemblyPath(Path.Combine(executionFolder, $"{assembly.Name}.dll")); var config = new ConfigurationBuilder() .AddJsonFile("Config\\SuperSocket.json") .Build();
三、依賴注入
FormatOptions options2 = new ServiceCollection() .AddOptions() .Configure<FormatOptions>(config.GetSection("Format")) .BuildServiceProvider() .GetService<IOptions<FormatOptions>>() .Value;