如何在ASP.NET核心中使用appsettings.json为不同的环境提供RavenDB的连接设置? RavenDB文档解释了如何使用app.config和web.config执行此操作,但我无法找到appsettings.json的任何内容。
正在向DocumentStoreHolder注入IOptions<RavenSettings>
正确的方式(看起来会是什么样的),还是有更好的选择?
到目前为止,这是代码:
appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Raven": {
"Url": "http://localhost:8080",
"DefaultDatabase": "MyDatabase"
}
}
startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConfiguration>(Configuration);
services.Configure<RavenSettings>(Configuration.GetSection("Raven"));
}
DocumentStoreHolder.cs
public class DocumentStoreHolder
{
private static Lazy<IDocumentStore> docStore = new Lazy<IDocumentStore>(CreateStore);
public static IDocumentStore Store
{
get { return docStore.Value; }
}
private static IDocumentStore CreateStore()
{
IDocumentStore store = new DocumentStore()
{
Url = "http://localhost:8080",
DefaultDatabase = "MyDatabase"
}.Initialize();
return store;
}
}
答案 0 :(得分:2)
最简单的方法是阅读各个值并直接在DocumentStore
上设置属性。在3.x中,RavenDB不支持从AppSettings.json
文件
答案 1 :(得分:0)
另一种方法可以是使用连接字符串而不是分离的配置,因此您可以根据asp net core平台中预期的当前环境名称解析连接字符串,并将连接字符串一直向下传递以获取DocumentStore以进行初始化第一次。
private static IDocumentStore InitRavenDb(string connectionString)
{
var optsBuilder = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString);
optsBuilder.Parse();
var opts = optsBuilder.ConnectionStringOptions;
return new DocumentStore
{
Url = opts.Url,
ApiKey = opts.ApiKey,
DefaultDatabase = opts.DefaultDatabase,
}.Initialize(true);
}
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddSingleton(_ => InitRavenDb(connectionString));