【发布时间】:2021-07-31 00:21:20
【问题描述】:
项目类型:asp.net core 2.2 (console application) web api 我正在使用 microsoft.Extensions.Options IOptions 的 Dependency Injection 将配置 appsettings.json 放入控制器中。它在我的本地开发机器上运行良好。但是 - 部署后 - 设置不会注入控制器。我添加了一个记录器来检查代码部署到的环境。在控制器构造函数中调查 config 变量时,我可以看到它有一个值,但应该从 appsettings 读取的属性为 null(参见代码) 在发布的文件夹中,我可以看到包含所有相关设置的 appsettings.json 文件。 我在这里错过了什么?
这是我的代码:
public class MyController : controllerBase
{
private ILogger<MyController> _logger;
private readonly IOptions<Myconfig> config;
public MyController(IOptions<Myconfig> config, ILogger<MyController> logger)
{
_logger = logger;
if (config == null)
{
logger.LogError("config is not being injected into the controller");
}
else if (config.Value != null) //this is the selected option but config.Value.ApiUri is null although it has value in the appsettings
{
logger.LogInformation($"config.Value.ApiUri:{config.Value.ApiUri}");
}
this.config = config;
....
}
}
在Startup.cs中,配置获取相关的appsetting入口:
public void ConfigureService(IServiceCollection services)
{
services.AddCors();
...
services.AddOptions();
services.AddHostedService<RepositoryManagerInitializer>();
services.Configure<Myconfig>(Configuration.GetSection("<relevant section key in the app settings>"));
}
【问题讨论】:
-
似乎没有注入 DI 配置 - 这似乎是一个错误的假设。部署后你的应用文件夹中有
appsettings.json吗? -
是的,我可以看到 appsettings.json。不仅如此 - 应用程序中的其他模块可以读取 appsettings 变量,但这些模块使用不同的方式来读取它们,而不是 DI
-
您能否详细说明“设置未注入控制器”的确切含义?你有例外吗?如果是这样,有什么例外?请张贴它的所有细节。否则,您看到的行为是什么,您期望的是什么?还可以尝试将您的问题转换为MRE,因为就目前而言,您的问题是不可重现的,并且是一个很好的解决方案。
-
@steven- 感谢您的评论 - 我已经编辑了代码和描述并添加了其他数据
-
请不要在问题中编辑解决方案公告。接受(即单击旁边的“勾选”)现有答案之一,如果有的话。如果现有答案尚未涵盖您的解决方案,您还可以创建自己的答案,甚至接受它。
标签: asp.net-core dependency-injection deployment asp.net-core-webapi appsettings