自定义配置经过如下形式引入: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(); }