Microsoft.Extensions.Configuration


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;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM