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;