自定义配置通过以下形式引入:
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)
{
// 1、注意:这里的 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();
}