【发布时间】:2019-01-29 17:39:54
【问题描述】:
我刚开始用 net core 2.1 构建一个 API。
我在 appsettings.json 中添加了我的连接字符串,我想访问它。
appsettings.json
"MySettings": {
"connectionString": "Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Subscription;Data Source=Test-Pc",
"Email": "abc@domain.com",
"SMTPPort": "5605"
}
首先我在 startup.cs 中添加了配置管理器,以便可以注入其他类
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MyConfig>(Configuration.GetSection("appsettings"));
}
我有一个初始化 SQLConnection 的类,但我需要注入 appsettings 以便读取连接字符串。
ConnectionManager.cs
public class CustomSqlConnection : IDisposable
{
private SqlConnection sqlConn;
private readonly IOptions<MyConfig> _myConfig;
public CustomSqlConnection(IOptions<MyConfig> _Config = null)
{
_myConfig = _Config;
string connectionString = _myConfig.Value.connectionString;
if (string.IsNullOrEmpty(connectionString))
{
throw new Exception(string.Format("Connection string was not found in config file"));
}
this.sqlConn = new SqlConnection(connectionString);
}
}
但是我想从另一个班级打电话。
CustomSqlConnection connection = new CustomSqlConnection()
但是,IOptions<MyConfig> _Config 显示为空。
初始化注入 IOptions 或任何其他接口的类的最佳做法是什么。
【问题讨论】:
-
也许
Configuration.GetSection("MySettings") -
只是需要澄清一下。您的
MyConfig类与`appsettings.json 相同,对吧? -
是的,它是一样的。顺便说一句,找不到 Configuration.GetSection。
标签: c# asp.net-core dependency-injection .net-core