我刚刚开始使用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
向我显示了null。
初始化注入IOptions或任何其他接口的类的最佳实践是什么。
答案 0 :(得分:1)
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; }
}
然后在“启动”中,您可以配置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
}
}
答案 1 :(得分:0)
也许首先要从json获取设置,以便您可以查看其是否正常运行,然后进行配置。
void log_to_console(const char *fmt, ...);
void log_to_file(const char *name, const char *fmt, ...);
#ifdef CONSOLE_VERBOSE_DEBUG
#define callThePropperDebugFct(...) log_to_console("s", __VA_ARGS__)
#elseif FILE_VERBOSE_DEBUG
#define callThePropperDebugFct(...) log_to_file(LOG_FILE, "%s", __VA_ARGS__)
#else
#define callThePropperDebugFct(...)
#endif
然后,如果可以正常工作:
var config = configuration.GetSection("MySettings").Get<MyConfig>();
此外,请确保已安装以下NuGet软件包:
Microsoft.Extensions.Configuration.Binder, Microsoft.Extensions.Configuration.Json, Microsoft.Extensions.DependencyInjection
答案 2 :(得分:0)
您可以在初始化CustomSqlConnection
对象的类中使用依赖项注入。
public class YourNewClass : IYourNewClass
{
private CustomSqlConnection _connection { get; set; }
//inject IOption here
public YourNewClass(IOptions<MyConfig> _config)
{
_connection = new CustomSqlConnection(_config); //use this instance for all the repository methods
}
}
更新:
您只需要在其他类中使用其接口IYourNewClass
注入该类。
public class SomeRandomClass
{
private IYourNewClass _newClass { get; set; }
public SomeRandomClass(IYourNewClass newClass)
{
_newClass = newClass;
}
}
然后在startup.cs中,先在mvc之前配置您的应用设置。
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.Development.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//do all needed service registrations
services.Configure<SpotMyCourtConfiguration>(Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//do all needed functionalities
app.UseMvc();
}
}