如何在Core 2.0中的ConfigurationBuilder中设置SetPath


142

如何在Core 2.0的ConfigurationBuilder中设置基本路径。

我用Google搜索,发现这个问题,这个来自微软的文档,以及2.0文档在线,但他们似乎使用的版本Microsoft.Extension.Configuration1.0.0-beta8

我想读appsettings.json。在Core 2.0中,有没有新的方法可以做到这一点?

using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace ConsoleApp2
{
    class Program
    {
        public static IConfigurationRoot Configuration { get; set; }

        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory()) // <== compile failing here
                .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            Console.WriteLine(Configuration.GetConnectionString("con"));
            Console.WriteLine("Press a key...");
            Console.ReadKey();
        }
    }
}

appsetting.json

{
  "ConnectionStrings": {
    "con": "connection string"
  }
}

更新: 除了按照Set指示的那样添加Microsoft.Extensions.Configuration.FileExtensions,我还需要添加Microsoft.Extensions.Configuration.Json来获取扩展名。AddJsonFile


2
UPDATE完成了工作!
克里斯·罗斯特

2
Microsoft.Extensions.Configuration.Json有依赖项Microsoft.Extensions.Configuration.FileExtensions,因此您只需要前者。
Johan B

朋友,请注意,该AddJsonFile("appsettings.json")方法不知道您的托管环境!使用.AddJsonFile($"appsettings.{_hostingEnvironment.EnvironmentName}.json")代替。:D
杰西

Answers:


302

SetBasePath扩展方法中定义Config.FileExtensions

您需要添加对Microsoft.Extensions.Configuration.FileExtensions包的引用。

要解决AddJsonFile,请添加对Microsoft.Extensions.Configuration.Json程序包的引用。


36
但是现在找不到“ AddJsonFile”方法。:DI还必须添加此程序包:“ Microsoft.Extensions.Configuration.Json”。
塔德吉

5
Microsoft.Extensions.Configuration.Json有依赖项Microsoft.Extensions.Configuration.FileExtensions,因此您只需要前者。
Johan B

61

我正在使用Visual Studio 2017 v15.5开发一个.NET Core 2控制台应用程序。正如其他人指出的那样,在添加Microsoft.Extensions.Configuration之后,我需要添加Microsoft.Extensions.Configuration.Json来使AddJsonFile()调用工作。这也使SetBasePath()通话有效。所以我不需要添加Configuration.FileExtensions。(我的代码在有和没有它的情况下都可以编译并运行。)

我还打了一个电话AddEnvironmentVariables(),为此我需要添加Configuration.EnvironmentVariables。我的代码如下:

  var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory()) // requires Microsoft.Extensions.Configuration.Json
                    .AddJsonFile("appsettings.json") // requires Microsoft.Extensions.Configuration.Json
                    .AddEnvironmentVariables(); // requires Microsoft.Extensions.Configuration.EnvironmentVariables
  Configuration = builder.Build();

有趣的是,using我唯一需要的陈述是using Microsoft.Extensions.Configuration


11
类文件中唯一必需的using语句应该是Microsoft.Extensions.Configuration。但是,您必须通过“管理NuGet包”项目选项显式添加NuGet依赖项“ Microsoft.Extensions.Configuration.Json”。其依赖项是“ Microsoft.Extensions.Configuration.FileExtensions”,因此将作为依赖项连接的一部分包括在内。这两个依赖关系将解决“ SetBasePath”和“ AddJsonFile”编译错误。
gregsonian '18

值得指出的是,这不再适用于VS for Mac Preview 8将当前目录设置为bin / netcoreapp2x
Chris Becke

不是学究的,而是Configuration.EnvironmentVariables== Microsoft.Extensions.Configuration.EnvironmentVariables。有几件名字相似的东西。
李·理查森

12

同时使用“ Microsoft.Extensions.Configuration”和“ Microsoft.Extensions.Configuration.Json”,这将解决问题。

https://www.nuget.org/packages/Microsoft.Extensions.Configuration/ https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Json/

这是示例“ ConnectionFactory”

using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace DataAccess.Infrastructure
{
 public class ConnectionFactory : IConnectionFactory
 {
    public ConnectionFactory()
    {
        var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
        Configuration = builder.Build();
    }


    public IConfigurationRoot Configuration { get; }
    public IDbConnection GetConnection
    {
        get
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            var conn = new SqlConnection(connectionString);
            conn.Open();
            return conn;
        }
    }

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects).
            }


            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
            // TODO: set large fields to null.

            disposedValue = true;
        }
    }

    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
    // ~ConnectionFactory() {
    //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    //   Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    public void Dispose()
    {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }
    #endregion
} }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.