How to SetBasePath in ConfigurationBuilder in Core 2.0
Asked Answered
P

5

204

How can I set the base path in ConfigurationBuilder in Core 2.0.

I have googled and found this question, this from Microsoft docs, and the 2.0 docs online but they seem to be using a version of Microsoft.Extension.Configuration from 1.0.0-beta8.

I want to read appsettings.json. Is there a new way of doing this in 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"
  }
}

UPDATE: In addition to adding Microsoft.Extensions.Configuration.FileExtensions as indicated below by Set I also needed to add Microsoft.Extensions.Configuration.Json to get the AddJsonFile extension.

Piotr answered 20/10, 2017 at 6:20 Comment(3)
The UPDATE made the work!Leptophyllous
Microsoft.Extensions.Configuration.Json has a dependency on Microsoft.Extensions.Configuration.FileExtensions, so you just need the former.Remaremain
Friends, PLEASE NOTE, the AddJsonFile("appsettings.json") method is not aware of your hosting environment! Use .AddJsonFile($"appsettings.{_hostingEnvironment.EnvironmentName}.json") instead. :DPhaidra
H
451

The SetBasePath extension method is defined in Config.FileExtensions.

You need to add a reference to the Microsoft.Extensions.Configuration.FileExtensions package.

To resolve AddJsonFile, add a reference to the Microsoft.Extensions.Configuration.Json package.

Hegarty answered 20/10, 2017 at 6:35 Comment(3)
But now the "AddJsonFile" method is not found. :D I had to add this package also: "Microsoft.Extensions.Configuration.Json".Encephalogram
Microsoft.Extensions.Configuration.Json has a dependency on Microsoft.Extensions.Configuration.FileExtensions, so you just need the former.Remaremain
do manage the nuget packages on solution level not the project levelFanya
G
80

I'm developing a .NET Core 2 console app using Visual Studio 2017 v15.5. As others have noted, after adding Microsoft.Extensions.Configuration I needed to add Microsoft.Extensions.Configuration.Json to get the AddJsonFile() call to work. This also made the SetBasePath() call work; so I did not need to add Configuration.FileExtensions . (My code compiles and runs both with and without it.)

I also had a call to AddEnvironmentVariables(), for which I needed to add Configuration.EnvironmentVariables. My code is as follows:

  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();

Interestingly, the only using statement I needed was using Microsoft.Extensions.Configuration.

Galaxy answered 30/12, 2017 at 20:49 Comment(3)
The only using statement necessary in the class file should be Microsoft.Extensions.Configuration. However, to the project you must explicitly add the NuGet dependency "Microsoft.Extensions.Configuration.Json" via Manage NuGet Packages project option. A dependency of this is "Microsoft.Extensions.Configuration.FileExtensions" and will therefore be included as part of the dependency wire-up. These two dependencies will solve both the "SetBasePath" and "AddJsonFile" compilation errors.Bistort
It's worth pointing out that this no longer works as VS for Mac Preview 8 sets the current directory to bin/netcoreapp2xApostrophize
Not to be pedantic but Configuration.EnvironmentVariables == Microsoft.Extensions.Configuration.EnvironmentVariables. There are several things with similar names.Oddfellow
V
15

Use both 'Microsoft.Extensions.Configuration' and 'Microsoft.Extensions.Configuration.Json' this will solve the problem.

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

Here is the sample '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
} }
Vagrant answered 5/1, 2018 at 7:11 Comment(0)
G
0

After adding reference if you are still unable to get the content of JSON.

Go to in properties of JSON (right-click on JSON file > properties) change "Copy to Output Directory" to "Copy Always"

check screenshot

Geest answered 5/5, 2022 at 12:54 Comment(0)
B
0

For those of you stumbling upon this while using .NET 8.

You'll need to following packages:

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
  </ItemGroup>

And the following using statement:

using Microsoft.Extensions.Configuration;

Now in your program.cs you can:

    // Build the configuration
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Environment.CurrentDirectory)
        .AddJsonFile($"appsettings.{environment}.json", optional: false) // Use the specified environment's file
        .Build();

More information in this article.

Bithynia answered 5/2 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.