自定義配置經過如下形式引入:json
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); // 自定義服務注入 services.Configure<ServiceOption>(Configuration.GetSection("ServiceOption")); services.AddSingleton<IMyService, MyService>(); }
public class MyService { ServiceOption option; public MyService(IOptions<ServiceOption> config) { // 一、注意:這裏的 config 能夠理解爲單例模式的對象,在程序中修改值會影響全局。 this.option= config.Value; } }
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) // 若不想配置被程序中熱更改,reloadOnChange 要設置爲 false .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); }