当前位置:首页 > Web开发 > 正文

[ASP.NET Core 3框架揭秘] Options[2]: 配置选项的正确使用方法[下篇]

2024-03-31 Web开发

标签:

原文:[ASP.NET Core 3框架揭秘] Options[2]: 配置选项的正确使用方法[下篇]

四、直接初始化Options东西

前面演示的几个实例具有一个配合的特征,即都给与配置系统来供给绑定Options东西的原始数据,实际上,Options框架具有一个完全独立的模型,可以称为Options模型。这个独立的Options模型自己并不依赖于配置系统,让配置系统来供给配置数据仅仅是通过Options模型的一个扩展点实现的。在很多情况下,可能并不需要将应用的配置选项界说在配置文件中,在应用启动时直接初始化可能是一种更便利快捷的方法。

class Program { static void Main() { var profile = new ServiceCollection() .AddOptions() .Configure<Profile>(it => { it.Gender = Gender.Male; it.Age = 18; it.ContactInfo = new ContactInfo { PhoneNo = "123456789", EmailAddress = "[email protected]" }; }) .BuildServiceProvider() .GetRequiredService<IOptions<Profile>>() .Value; Console.WriteLine($"Gender: {profile.Gender}"); Console.WriteLine($"Age: {profile.Age}"); Console.WriteLine($"Email Address: {profile.ContactInfo.EmailAddress}"); Console.WriteLine($"Phone No: {profile.ContactInfo.PhoneNo}\n"); } }

我们依然沿用前面演示的应用场景,此刻摒弃配置文件,转而给与编程的方法直接对用户信息进行初始化,所以需要对措施做如上改写。在挪用IServiceCollection接口的Configure<Profile>扩展要领时,不需要再指定一个IConfiguration东西,而是操作一个Action<Profile>类型的委托对作为参数的Profile东西进行初始化。措施运行后会在控制台上孕育产生下图所示的输出功效。

具名Options同样可以给与类似的方法进行初始化。如果需要按照指定的名称对Options进行初始化,那么挪用要领时就需要指定一个Action<TOptions,String>类型的委托东西,该委托东西的第二个参数暗示Options的名称。在如下所示的代码片段中,我们通过类似的方法设置了两个用户(foo和bar)的信息,,然后操作IOptionsSnapshot<TOptions>处事将它们分袂提取出来。

class Program { static void Main() { var optionsAccessor = new ServiceCollection() .AddOptions() .Configure<Profile>("foo", it => { it.Gender = Gender.Male; it.Age = 18; it.ContactInfo = new ContactInfo { PhoneNo = "123", EmailAddress = "[email protected]" }; }) .Configure<Profile>("bar", it => { it.Gender = Gender.Female; it.Age = 25; it.ContactInfo = new ContactInfo { PhoneNo = "456", EmailAddress = "[email protected]" }; }) .BuildServiceProvider() .GetRequiredService<IOptionsSnapshot<Profile>>(); Print(optionsAccessor.Get("foo")); Print(optionsAccessor.Get("bar")); static void Print(Profile profile) { Console.WriteLine($"Gender: {profile.Gender}"); Console.WriteLine($"Age: {profile.Age}"); Console.WriteLine($"Email Address: {profile.ContactInfo.EmailAddress}"); Console.WriteLine($"Phone No: {profile.ContactInfo.PhoneNo}\n"); }; } }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31824.html