旧类库使用app.config自动读取配置值.在新的类库中,您必须添加此功能.Startup.cs用于读取app.settings在类库中,您还必须添加Startup.cs.
在你的project.json
确保你有依赖
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"
添加一个过appsettings.json
孔add - new item
.过滤json
{ "Data": { "MyDb": { "ConnectionString": "Server=.;Database=MyDb;Trusted_Connection=True;MultipleActiveResultSets=true" } } }
您可以调用您的连接MyDb或DefaultConnection.
添加一个Startup.cs
来放置代码来读取appsettings.json
.
请参阅下面的Startup
构造函数方法.
例如
using Microsoft.Data.Entity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace MyProject { public class Startup { public IConfigurationRoot Configuration { get; set; } public Startup() { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(Configuration["Data:MyDb:ConnectionString"])); } } }
在上面的例子中引用
Configuration["Data:MyDb:ConnectionString]
将返回一种IConfigurationRoot,而不是字符串.
要获取字符串值,请尝试以下操作
string connection = Configuration.Get("Data:MyDb:ConnectionString");