我刚开始使用 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中添加了配置管理器,这样我就可以在其他类中注入(inject)
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MyConfig>(Configuration.GetSection("appsettings"));
}
我有一个初始化 SQLConnection 的类,但我需要注入(inject)应用程序设置以便读取连接字符串。
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);
}
}
但是我想从另一个类(class)打电话。
CustomSqlConnection connection = new CustomSqlConnection()
然而,IOptions<MyConfig> _Config
显示我为空。
初始化注入(inject) IOptions 或任何其他接口(interface)的类的最佳实践是什么。
最佳答案
Configuration.GetSection("MySettings")
将尝试在 appsettings.json 文件中找到“MySettings”部分。
MySettings
类应该如下所示
public class MySettings
{
public string connectionString { get; set; }
public string Email { get; set; }
public string SMTPPort { get; set; }
}
然后在 Startup 中,您将能够配置 MySettings
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MyConfig>(Configuration.GetSection("MySettings"));
}
和设置的使用
public class SomeClass
{
private readonly MySettings _settings;
public SomeClass(IOptions<MySettings> setitngs)
{
_settings = setitngs.Value // notice of using a .Value property
}
}
关于c# - 使用 IOptions 注入(inject)问题初始化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54417113/