(精华)2020年9月15日 ASP.NET Core 配置选项底层详解

1.内存配置文件为属性赋值

public static class Sample01
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }

        public AppConfigDemo(IConfiguration config)
        {
            Name = config["Name"];
            StartDate = config["StartDate"];
            EndDate = config["EndDate"];
        }
    }

    public static void Run()
    {
        var source = new Dictionary<string, string>
        {
            ["Name"] = "AppConfig",
            ["StartDate"] = "2020年5月1日",
            ["EndDate"] = "2020年5月5日"
        };

        //添加内存配置文件
        var config = new ConfigurationBuilder()
            // .Add(new MemoryConfigurationSource{InitialData = source})
            .AddInMemoryCollection(source)
            .Build();

        var options = new AppConfigDemo(config);
        Console.WriteLine($"Name:{options.Name}");
        Console.WriteLine($"StartDate:{options.StartDate}");
        Console.WriteLine($"EndDate:{options.EndDate}");
    }
}

2.内存配置文件绑定对象

public static class Sample02
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }
    }

    public static void Run()
    {
        var source = new Dictionary<string, string>
        {
            ["Name"] = "AppConfig",
            ["StartDate"] = "2020年5月1日",
            ["EndDate"] = "2020年5月5日"
        };

        var options = new ConfigurationBuilder()
            .AddInMemoryCollection(source)
            .Build()
            .Get<AppConfigDemo>();

        Console.WriteLine($"Name:{options.Name}");
        Console.WriteLine($"StartDate:{options.StartDate}");
        Console.WriteLine($"EndDate:{options.EndDate}");
    }
}

3.JSON文件配置绑定对象

public static class Sample03
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }

        public Behavior Behavior { get; set; }
    }

    public class Behavior
    {
        public bool IsRead { get; set; }
        public bool IsWrite { get; set; }
    }

    public static void Run()
    {
        var options = new ConfigurationBuilder()
            //添加Json配置文件
            //.Add(new JsonConfigurationSource{Path = "appsettings.json"})
            .AddJsonFile("appsettings.json")
            .Build()
            .Get<AppConfigDemo>();

        Console.WriteLine($"Name:{options.Name}");
        Console.WriteLine($"StartDate:{options.StartDate}");
        Console.WriteLine($"EndDate:{options.EndDate}");
        Console.WriteLine($"Behavior.IsRead:{options.Behavior.IsRead}");
        Console.WriteLine($"Behavior.IsWrite:{options.Behavior.IsWrite}");
    }
}

4.监控配置文件

public static class Sample04
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }

        public Behavior Behavior { get; set; }
    }

    public class Behavior
    {
        public bool IsRead { get; set; }
        public bool IsWrite { get; set; }
    }

    public static void Run()
    {
        var config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", true, true)
            .Build();

        Read(config.Get<AppConfigDemo>());
        ChangeToken.OnChange(() => config.GetReloadToken(), () =>
        {
            Read(config.Get<AppConfigDemo>());
        });
        Console.Read();
    }

    public static void Read(AppConfigDemo options)
    {
        Console.Clear();
        Console.WriteLine($"Name:{options.Name}");
        Console.WriteLine($"StartDate:{options.StartDate}");
        Console.WriteLine($"EndDate:{options.EndDate}");
        Console.WriteLine($"Behavior.IsRead:{options.Behavior.IsRead}");
        Console.WriteLine($"Behavior.IsWrite:{options.Behavior.IsWrite}");
    }
}

5.环境变量配置文件

public static class Sample05
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string Ver { get; set; }
    }


    public static void Run()
    {
        Environment.SetEnvironmentVariable("APP_NAME", "AppDemo");
        Environment.SetEnvironmentVariable("APP_VER", "Alpha");

        var config = new ConfigurationBuilder()
            .AddEnvironmentVariables("APP_")
            .Build()
            .Get<AppConfigDemo>();

        Console.WriteLine($"Name:{config.Name}");
        Console.WriteLine($"Ver:{config.Ver}");
    }
}

6.命令行变量配置文件

public static class Sample06
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string Version { get; set; }
    }

    public static void Run(string[] args)
    {
        var mapping = new Dictionary<string, string>()
        {
            //参数映射
            ["-n"] = "Name",
            ["-ver"] = "Version"
        };

        var config = new ConfigurationBuilder()
            .AddCommandLine(args, mapping)
            .Build()
            .Get<AppConfigDemo>();

        Console.WriteLine($"Name:{config.Name}");
        Console.WriteLine($"Ver:{config.Version}");
    }
}

7.XML文件配置绑定对象

public static class Sample07
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }

        public Behavior Behavior { get; set; }
    }

    public class Behavior
    {
        public bool IsRead { get; set; }
        public bool IsWrite { get; set; }
    }

    public static void Run()
    {
        var options = new ConfigurationBuilder()
            .AddXmlFile("App.config")
            .Build()
            .GetSection(nameof(AppConfigDemo))//获取配置名称
            .Get<AppConfigDemo>();
        
        Console.WriteLine($"Name:{options.Name}");
        Console.WriteLine($"StartDate:{options.StartDate}");
        Console.WriteLine($"EndDate:{options.EndDate}");
        Console.WriteLine($"Behavior.IsRead:{options.Behavior.IsRead}");
        Console.WriteLine($"Behavior.IsWrite:{options.Behavior.IsWrite}");
    }
}

8.Options使用配置文件

public static class Sample01
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }

        public Behavior Behavior { get; set; }
    }

    public class Behavior
    {
        public bool IsRead { get; set; }
        public bool IsWrite { get; set; }
    }

    public static void Run()
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        var serviceProvider = new ServiceCollection()
            .AddOptions()//添加选项服务
            .Configure<AppConfigDemo>(configuration)//绑定选项
            .BuildServiceProvider();

        var options = serviceProvider.GetRequiredService<IOptions<AppConfigDemo>>();

        var appConfig = options.Value;

        Console.WriteLine($"Name:{appConfig.Name}");
        Console.WriteLine($"StartDate:{appConfig.StartDate}");
        Console.WriteLine($"EndDate:{appConfig.EndDate}");
        Console.WriteLine($"Behavior.IsRead:{appConfig.Behavior.IsRead}");
        Console.WriteLine($"Behavior.IsWrite:{appConfig.Behavior.IsWrite}");
    }
}

9.Options匿名使用多配置文件

public static class Sample02
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }
    }


    public static void Run()
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("muti.json")
            .Build();

        var serviceProvider = new ServiceCollection()
            .AddOptions()
            .Configure<AppConfigDemo>("DefaultApp", configuration.GetSection("DefaultApp"))
            .Configure<AppConfigDemo>("CustomApp", configuration.GetSection("CustomApp"))
            .BuildServiceProvider();
		//带有命名功能选项对象
        var options = serviceProvider.GetRequiredService<IOptionsSnapshot<AppConfigDemo>>();

        var defaultApp = options.Get("DefaultApp");
        var customApp = options.Get("CustomApp");

        Console.WriteLine($"Name:{defaultApp.Name}");
        Console.WriteLine($"StartDate:{defaultApp.StartDate}");
        Console.WriteLine($"EndDate:{defaultApp.EndDate}");


        Console.WriteLine($"Name:{customApp.Name}");
        Console.WriteLine($"StartDate:{customApp.StartDate}");
        Console.WriteLine($"EndDate:{customApp.EndDate}");
    }
}

10.Options监控功能配置文件

public static class Sample03
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }

        public Behavior Behavior { get; set; }
    }

    public class Behavior
    {
        public bool IsRead { get; set; }
        public bool IsWrite { get; set; }
    }

    public static void Run()
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", false, true)
            .Build();

        var serviceProvider = new ServiceCollection()
            .AddOptions()
            .Configure<AppConfigDemo>(configuration)
            .BuildServiceProvider();
        //带有监控功能选项对象
        var options = serviceProvider.GetRequiredService<IOptionsMonitor<AppConfigDemo>>();

        options.OnChange(appConfig =>
        {
            Console.Clear();
            Console.WriteLine($"Name:{appConfig.Name}");
            Console.WriteLine($"StartDate:{appConfig.StartDate}");
            Console.WriteLine($"EndDate:{appConfig.EndDate}");
            Console.WriteLine($"Behavior.IsRead:{appConfig.Behavior.IsRead}");
            Console.WriteLine($"Behavior.IsWrite:{appConfig.Behavior.IsWrite}");
        });

        Console.Read();

    }
}

11.Options配置文件初始化值

public static class Sample05
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }
    }

    public static void Run()
    {
        var serviceProvider = new ServiceCollection()
            .AddOptions()
            .Configure<AppConfigDemo>(config =>
            {
                config.Name = "DefaultApp";
                config.StartDate = "2020/5/6";
                config.EndDate = "2020/5/7";
            })
            .BuildServiceProvider();

        var options = serviceProvider.GetRequiredService<IOptions<AppConfigDemo>>();
        var appConfig = options.Value;

        Console.WriteLine($"Name:{appConfig.Name}");
        Console.WriteLine($"StartDate:{appConfig.StartDate}");
        Console.WriteLine($"EndDate:{appConfig.EndDate}");
    }
}

12.Options参数校验配置文件

public static class Sample06
{
    public class AppConfigDemo
    {
        public string Name  { get; set; }
        public string Version { get; set; }
    }

    public static void Run(string[] args)
    {
        var mapping = new Dictionary<string, string>()
        {
            ["-n"] = "Name",
            ["-ver"] = "Version"
        };

        var config = new ConfigurationBuilder()
            .AddCommandLine(args, mapping)
            .Build();

        var services = new ServiceCollection();
        services.AddOptions<AppConfigDemo>()
            .Configure(options =>
            {
                options.Name = config["Name"] ?? "";
                options.Version = config["Version"] ?? "";
            })
            .Validate(demo => demo.Version.StartsWith("Alpha"), "Version 参数无效")
            .Validate(demo => demo.Name.EndsWith("App"), "Name 参数无效");

        try
        {
            var options = services.BuildServiceProvider()
                .GetRequiredService<IOptions<AppConfigDemo>>().Value;
            Console.WriteLine(options.Name);
            Console.WriteLine(options.Version);
        }
        catch (OptionsValidationException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页