【问题标题】:Using ASP.NET Core configuration settings for RavenDB connections为 RavenDB 连接使用 ASP.NET Core 配置设置
【发布时间】:2017-03-20 12:20:20
【问题描述】:

如何在 ASP.NET Core 中使用 appsettings.json 为不同环境提供到 RavenDB 的连接设置? RavenDB 文档解释了如何使用 app.config 和 web.config 执行此操作,但我找不到 appsettings.json 的任何内容。

IOptions<RavenSettings> 注入 DocumentStoreHolder 是正确的方法吗(这会是什么样子),还是有更好的选择?

到目前为止的代码如下:

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;
        }
    }

【问题讨论】:

    标签: c# asp.net-core ravendb


    【解决方案1】:

    最简单的方法是读取单个值并直接在DocumentStore 上设置属性。在 3.x 中,RavenDB 不支持从AppSettings.json 文件中读取配置

    【讨论】:

      【解决方案2】:

      另一种方法是使用连接字符串而不是单独的配置,因此您可以根据当前环境名称解析连接字符串,如在 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));
      

      【讨论】:

        猜你喜欢
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 2017-01-14
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多