我无法从appsettings.json中检索值,当我运行下面的代码时,出现错误
System.NullReferenceException: 'Object reference not set to an instance of an object.
appSettings.json
"MySettings": {
"ConnectionString": "",
"Provider": "Microsoft.EntityFrameworkCore.SqlServer" }
Startup.cs
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.Configure<MySettings>(Configuration.GetSection("MySettings"));
}
MySettings.cs
public class MySettings
{
public static string ConnectionString { get; set; }
public static string Provider { get; set; }
}
TestDriveDatabase.cs
public class TestDriveDatabase
{
private IDatabase objDLOperation;
public TestDriveDatabase(string strConnectionstring)
{
objDLOperation = GetDataLayerInstance(strConnectionstring);
}
public IDatabase GetDataLayerInstance(string strConnectionstring)
{
IDatabase objInstance = null;
var provider = MySettings.Provider;
if (provider == "Microsoft.EntityFrameworkCore.SqlServer")
{
objInstance = new SQLDatabase(strConnectionstring);
}
else if (provider == "Npgsql.EntityFrameworkCore.PostgreSQL")
{
objInstance = new PostgreDatabase(strConnectionstring);
}
return objInstance;
}
}
很遗憾,从appsettings.json
到MySettings
的映射没有发生,变量provider
始终保持为空。这有什么不对吗?
答案 0 :(得分:1)
首先删除static关键字,您不能将配置值映射到静态属性
public class MySettings
{
public string ConnectionString { get; set; }
public string Provider { get; set; }
}
其次,将MySettings
注入TestDriveDatabase
。
public class TestDriveDatabase
{
private IDatabase objDLOperation;
private readonly MySettings settings;
public TestDriveDatabase(IOptions<MySettings> mySettings)
{
this.settings = mySettings.Value;
objDLOperation = GetDataLayerInstance(strConnectionstring);
}
public IDatabase GetDataLayerInstance(string strConnectionstring)
{
IDatabase objInstance = null;
var provider = settings.Provider;
if (provider == "Microsoft.EntityFrameworkCore.SqlServer")
{
objInstance = new SQLDatabase(settings.Connectionstring);
}
else if (provider == "Npgsql.EntityFrameworkCore.PostgreSQL")
{
objInstance = new PostgreDatabase(settings.Connectionstring);
}
return objInstance;
}
}