我有一个。 NET核心控制台应用程序实现IHostedService并用的DbContext定义另一个项目的引用。这是的DbContext的控制台应用程序配置:
IHost host = new HostBuilder()
.ConfigureHostConfiguration(configHost =>
{
configHost.SetBasePath(Directory.GetCurrentDirectory());
configHost.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configHost.AddCommandLine(args);
})
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configApp.AddJsonFile($"appsettings.json", true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
configApp.AddCommandLine(args);
})
.ConfigureServices((hostContext, services) =>
{
services.AddDbContext<MyAppDbContext>(options => options.UseNpgsql(hostContext.Configuration.GetConnectionString("DefaultConnection")));
services.AddHostedService<ApplicationLifetimeHostedService>();
})
.Build();
现在,在应用程序生命周期托管服务的OnStarted()方法,我有:
using (var _context = new MyAppDbContext())
{
...
_context.SaveChanges();
}
为什么MyAppDbContext采取从的DbContext定义类的OnConfiguring方法连接字符串值(硬编码,从脚手架生成),而不是从AppSettings的。{ASPNETCORE_ENVIROMENT}上传.json()?
先感谢您!
根据您的配置,目前IHostBuilder
对非Web应用程序和模拟类属配置,这最终将取代IWebHostBuilder
。不过,你不需要那些......在你的情况下,你将与CreateDefaultBuilder
更好。
两者都默认提供,具有更精细的控制。主要产品由制造商和他们编译或建立提供的默认服务。
直接回答您的问题,虽然,在你的顶线,你缺少了以下内容:
var host = new HostBuilder()
.ConfigureHostConfiguration(configuration =>
{
// For brevity, removed some.
configuration.AddJsonFile("appsettings.json", false, true);
}
这就是为什么你的appsettings.json
不工作。该ConfigureHostConfiguration
将通过随身携带的ConfigureAppConfiguration
。
主机配置自动流向应用配置(ConfigureAppConfiguration和该应用程序的其余部分)。
没有提供默认包含。你必须明确指定的任何配置提供的应用程序需要在ConfigureHostConfiguration,其中包括:
- 文件配置(例如,从hostsettings.json文件)。
- 环境变量配置。
- 命令行参数配置。
- 任何其它所需的配置提供者。