namespace ConsoConfiguration { public class Program { //Configuration: Represents a set of key/value application configuration properties. //表示一组键/值 应用程序配置属性。 private static IConfiguration Configuration { set; get; } static void Main(string[] args) { //ConfigurationBuilder:Used to build key/value based configuration settings for use in an application //用于生成基于键/值的配置设置,以便在应用程序中使用 //这个主要用于配置管理 var Configure = new ConfigurationBuilder(); Configure.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); //Build==》Configure var configuration = Configure.Build();//启动 var GetSectionValue = configuration.GetSection("ConnectionStrings").GetValue<string>("wms"); var GetConnectionStringValue = configuration.GetConnectionString("wms"); //↑↑↑上面是把基于Key/Value的配置给配置好了↑↑↑↑↑↑↑↑↑↑↑ //↓↓↓给Host添加所需要的服务↓↓↓↓↓↓ var builder = new HostBuilder(); //配置Loggering的服务 builder.ConfigureLogging((hostbuildercontext, loggering) => { loggering.AddConsole(); }); //配置Services的服务 //ConfigureServices:Adds services to the container. This can be called multiple times and the results will be additive. //向容器添加服务。这可以多次调用,结果将是相加的。 builder.ConfigureServices((hostbuildercontext, ServicesCollections) => { //hostbuildercontext.Configuration: //这个Microsoft.Extensions.Configuration.IConfiguration包含应用程序和Microsoft.Extensions.Hosting.i主机。 Configuration = hostbuildercontext.Configuration;
//链接SqlConnectionString ServicesCollections.AddDbContext<WMSContext>(o => o.UseSqlServer(configuration.GetSection("").GetValue<string>(""))); //常见的服务NuGet ServicesCollections.AddHttpClient(); ServicesCollections.AddOptions(); //生命周期 ServicesCollections.AddSingleton(Configuration); }); //Build==》用来启动Host var host = builder.Build(); using (host) { host.Run(); } Console.WriteLine("Hello World!"); } } }
{ "ConnectionStrings": { "wms": "Data Source=;Initial Catalog=WMS;Persist Security Info=True;User ID=wms;Password=", "acc_hub": "Data Source=;pwd=;uid=sa;database=;" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AppSettings": { "Name": "tom", "Age": "15" }, "AllowedHosts": "*" }