【发布时间】:2018-12-27 19:29:16
【问题描述】:
在我的 Asp.net Core 2.0 应用程序中,我正在尝试按照@Nkosi here 的建议,在我的类库项目中实现不使用 IConfiguration 构造函数依赖项来连接字符串的设计。
在这种方法中,它无法将配置实例绑定到类型的新实例,如以下代码行所示
public void ConfigureServices(IServiceCollection services) {
//...
var settings = Configuration
.GetSection("ConnectionStrings:OdeToFood")
.Get<ConnectionSetings>();
//...verify settings (if needed)
services.AddSingleton(settings);
}
public class ConnectionSetings
{
public string Name { get; set; }
}
我可以看到Configuration.GetSection("ConnectionStrings:OdeToFood") 返回“Key”、“Path”和“Value”属性,但它无法进行绑定并在设置中返回 null。
我看到过类似的问题,其中 ppl 推荐了如下解决方案,但没有一个对我有用。
services.Configure<ConnectionsSetings>(Configuration.GetSection("ConnectionStrings:OdeToFood"));
还有,
Configuration
.GetSection("ConnectionStrings:OdeToFood").Bind<>
下面是appsettings.json
{
"Greeting": "Hello!!!",
"ConnectionStrings": {
"OdeToFood": "Server=(localdb)\\MSSQLLocalDB;Database=OdeToFood;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
以下是 Configuration.GetSection 输出的即时窗口屏幕截图,我可以在其中看到键、路径和值
从下面的截图可以看出设置变量为空
【问题讨论】:
-
设置是否来自 appsettings.json 文件?如果是这样,这个文件是配置为“内容”还是“复制到输出目录”?
-
是的,就是appsetting.json文件,配置为内容
-
appsettings.json的结构是什么?
-
@LearningCurve 向我们展示您的应用设置 json 文件
-
不在我的电脑上,但它是 ConnectionStrings 部分的基础,其中包含 OdeToFood 连接字符串。别忘了,Configuration.Getsection 可以读取文件并提供值。没有发生的是到 ConnectionsSeting 文件的映射
标签: c# dependency-injection asp.net-core-2.0 class-library asp.net-core-mvc-2.0