[英]Using ASP.NET Core configuration settings for RavenDB connections
How do I use appsettings.json in ASP.NET core to provide connection settings to RavenDB for different environments? 如何在ASP.NET Core中使用appsettings.json来提供针对不同环境的RavenDB连接设置? The RavenDB docs explain how to do this with app.config and web.config, but I can't find anything for appsettings.json. RavenDB文档解释了如何使用app.config和web.config进行此操作,但是我找不到appsettings.json的任何内容。
Is injecting an IOptions<RavenSettings>
into the DocumentStoreHolder the right way to go (and what would this look like), or is there a better option? 是否将IOptions<RavenSettings>
注入DocumentStoreHolder是正确的方法(看起来像什么),还是有更好的选择?
Here's the code so far: 到目前为止的代码如下:
appsettings.json appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Raven": {
"Url": "http://localhost:8080",
"DefaultDatabase": "MyDatabase"
}
}
startup.cs startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConfiguration>(Configuration);
services.Configure<RavenSettings>(Configuration.GetSection("Raven"));
}
DocumentStoreHolder.cs 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;
}
}
The easiest is to read the individual values and set the properties directly on the DocumentStore
. 最简单的方法是读取各个值,然后直接在DocumentStore
上设置属性。 In 3.x RavenDB doesn't support reading the configuration from the AppSettings.json
file 在3.x中,RavenDB不支持从AppSettings.json
文件中读取配置
A different approach could be by using connection strings instead of separated configurations, so you can resolve connection string depending on current environment name as expected in asp net core platform, and pass the connection string all way down to get DocumentStore initialized for the first time. 一种不同的方法是使用连接字符串而不是单独的配置,因此您可以根据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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.