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;

 

posted @   流沙河小妖  阅读(1260)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示