我有一个ASP.NET 5 MVC Web应用程序,在Startup.cs中,我看到了公共属性
IConfigurationRoot Configuration
被设置为 builder.Build();
在整个MVC Web应用程序中,我可以轻松完成
Startup.Configuration["Data:DefaultConnection:ConnectionString"]
从appsettings.json
文件中获取conn字符串。
如何appsettings.json
使用构造函数注入获取在ASP.NET 5 MVC中指定的连接字符串,该连接字符串向下传递到我的存储库类库中?
更新:
这是所有其他存储库都继承自的基本存储库(如您所见,现在我在这里有一个硬编码的连接字符串):
public class BaseRepo
{
public static string ConnectionString = "Server=MYSERVER;Database=MYDATABASE;Trusted_Connection=True;";
public static SqlConnection GetOpenConnection()
{
var cs = ConnectionString;
var connection = new SqlConnection(cs);
connection.Open();
return connection;
}
}
在我的appsettings.json文件中的asp.net 5 Web应用程序中,我具有以下等同于向.net 4.5 Webapp中的web.config添加连接字符串的情况:
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=MYSERVER;Database=MYDATABASE;Trusted_Connection=True;"
}
}
另外,在我的asp.net 5 Web应用程序中,我的Startup.cs中包含以下默认代码,该代码将站点配置加载到IConfigurationRoot类型的公共属性中:
public IConfigurationRoot Configuration { get; set; }
// Class Constructor
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
现在,在我的asp.net Web应用程序中,如果我想访问任何appsettings,我可以简单地执行以下操作: Startup.Configuration["Data:DefaultConnection:ConnectionString"]
但不幸的是,我无法从我的班级库中做到这一点。
如果有人想找出答案,请按照以下步骤进行重现:
更新后,我还是不太明白。这是我的代码:
public class BaseRepo
{
private readonly IConfigurationRoot config;
public BaseRepo(IConfigurationRoot config)
{
this.config = config;
}
}
此类声明不起作用,因为BaseRepo现在需要构造函数参数。
public class CustomerRepo : BaseRepository, ICustomerRepo
{
public Customer Find(int id)
{
using (var connection = GetOpenConnection())
{
...
}
}
}
在您的Startup.cs文件上,添加以下方法
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton(_ => Configuration);
}
然后像这样更新您的BaseRepo类
public class BaseRepo {
private readonly IConfiguration config;
public BaseRepo(IConfiguration config) {
this.config = config;
}
public SqlConnection GetOpenConnection() {
string cs = config["Data:DefaultConnection:ConnectionString"];
SqlConnection connection = new SqlConnection(cs);
connection.Open();
return connection;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句