Is Configurationmanager.Appsettings Available in .Net Core 2.0

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.

Credits goes to @JeroenMostert for giving me the solution.

Does ConfigurationManager work with ASP.NET core's appsettings.json?

ConfigurationManager does not work with appsettings.json, instead of ConfigurationManager you have to use ConfigurationBuilder class for add json file in startup.cs file.

1.Put below code in appsettings.json

"ConnectionStrings": {
"connectionstring ": "Data Source=Demo_server\\SQLEXPRESS01;Initial Catalog=Demo_DB;Persist Security Info=True; User ID=sa;Password=Password@123" }

2.Put below code in startup.cs.

 public Startup(IHostingEnvironment env)
{
Configuration = new ConfigurationBuilder().AddJsonFile("appSettings.json").Build();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
ConnectionString = Configuration["ConnectionStrings:connectionstring"]; // Get Connection String from Appsetting.json
}

3.Create ConnectionStringUtility class for get connection string from Startup.cs file.

public class ConnectionStringUtility
{
public static string GetConnectionString()
{
return Startup.ConnectionString;
}
}

4.Get Connectionstring in connection variable and use this connection string where ever you want.

public string Connectionstring = ConnectionStringUtility.GetConnectionString();

.Net Core 2.0 appsettings with .net full framework using ConfigurationManager

Trick is to use ConfigurationManager.AppSettings.Set method to prepopulate ConfigurationManager.AppSettings from .NET Core so class libraries can use it later.

I am using following classes to add json settings into ConfigurationManager.

public class CustomJsonConfigurationProvider : JsonConfigurationProvider
{
public CustomJsonConfigurationProvider(JsonConfigurationSource source) : base(source) { }

public override void Load()
{
base.Load();
foreach (string key in Data.Keys)
{
string[] keyParts = key.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
ConfigurationManager.AppSettings.Set(keyParts[keyParts.Length - 1], Data[key]);
}
}
}

public class CustomJsonConfigurationSource : JsonConfigurationSource
{
public override IConfigurationProvider Build(IConfigurationBuilder builder)
{
FileProvider = FileProvider ?? builder.GetFileProvider();
return new CustomJsonConfigurationProvider(this);
}
}

public static class CustomConfiguratorExtensions
{
public static IConfigurationBuilder AddCustomJsonFile(this IConfigurationBuilder builder, string path)
{
return AddCustomJsonFile(builder, provider: null, path: path, optional: false, reloadOnChange: false);
}

public static IConfigurationBuilder AddCustomJsonFile(this IConfigurationBuilder builder, string path, bool optional)
{
return AddCustomJsonFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false);
}

public static IConfigurationBuilder AddCustomJsonFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange)
{
return AddCustomJsonFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange);
}

public static IConfigurationBuilder AddCustomJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange)
{
if (provider == null && Path.IsPathRooted(path))
{
provider = new PhysicalFileProvider(Path.GetDirectoryName(path));
path = Path.GetFileName(path);
}

var source = new CustomJsonConfigurationSource
{
FileProvider = provider,
Path = path,
Optional = optional,
ReloadOnChange = reloadOnChange
};

builder.Add(source);

return builder;
}
}

Usage:

builder.ConfigureAppConfiguration((w, c) =>
{
c.AddCustomJsonFile("appsettings.json");
});

Analog of ConfigurationManager in dotnet 6 and netstandard 2.0, and Protected Section

I came to this solution to achieve this functionality. It utilizes Singleton pattern to make this happen. And again, this is a prototype. 3 Projects

  1. Configuration library, contains the following code for singleton. This code loads settings in any way you want.
public class ConfigSingleton
{
private static ConfigSingleton _instance;

static ConfigSingleton()
{
_instance = new ConfigSingleton();
_instance.Init();
}

public static ConfigSingleton Instance { get { return _instance; } }
public string StringSetting { get; private set; }
public int IntSetting { get; private set; }
public bool BoolSetting { get; private set; }
public int InstanceId { get; private set; }

private void Init()
{
IConfiguration Configuration = new msc.ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
//.AddUserSecrets("bbbb",)

//.AddCommandLine(args)
.Build();

var section = Configuration.GetSection("CustomSettingsSection");
StringSetting = section.GetValue<string>("StringSetting");
IntSetting = section.GetValue<int>("NumericSetting");
BoolSetting = section.GetValue<bool>("BoolSetting");
InstanceId = Guid.NewGuid().ToString().GetHashCode();
}

}

  1. Consuming library. Things are simple here
public static class ConfigWrapper
{
public static ConfigSingleton GetConfig()
{
return ConfigSingleton.Instance;
}
}

  1. Consuming console app, which consumes both libraries above and proves that we have same singleton object loaded with our settings
public static void Main(string[] args)
{
Console.WriteLine("wrapper config id: " + netstandard20.lib.ConfigWrapper.GetConfig().InstanceId);

var boolSet = netstandard20.lib.ConfigWrapper.GetConfig().BoolSetting;
Console.WriteLine("Bool from wrapper: " + boolSet);

var intSet = netstandard20.lib.ConfigWrapper.GetConfig().IntSetting;
Console.WriteLine("int from wrapper: " + intSet);

var strSet = netstandard20.lib.ConfigWrapper.GetConfig().StringSetting;
Console.WriteLine("string from wrapper: " + strSet);

Console.WriteLine("= = = = = = = = = = = = = = = = = = = = = =");

Console.WriteLine("config id: " + netstandard20.lib.config.ConfigSingleton.Instance.InstanceId);

boolSet = netstandard20.lib.config.ConfigSingleton.Instance.BoolSetting;
Console.WriteLine("Bool from config: " + boolSet);

intSet = netstandard20.lib.config.ConfigSingleton.Instance.IntSetting;
Console.WriteLine("int from config: " + intSet);

strSet = netstandard20.lib.config.ConfigSingleton.Instance.StringSetting;
Console.WriteLine("string from config: " + strSet);

Console.Read();
}

This works. Not sure if this is a "great idea"

How to use System.Configuration.ConfigurationManager in .netstanard library for .net core and .netframework

As I said, you should not depend directly on how the configuration is obtained in a class library. Keep your class library flexible.

Don't do this in your class library:

public void UpdateProductName(int productId, string name)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"]))
{
connection.ExecuteNonQuery("UPDATE dbo.Products SET Name = @Name WHERE Id = @ProductId", new { ProductId = productId, Name = name });
}
}

By directly using ConfigurationManager in your class library, you've tied the class to only allowing one form of obtaining the connection string. That means if you want to use appsettings.json, or environment variables, or KeyVault, or any other method of obtaining configuration, you can't.

Instead, do this:

public class MyDatabaseRepository
{
readonly string _connectionString;

public MyDatabaseRepository(string connectionString)
{
_connectionString = connectionString;
}
}

public void UpdateProductName(int productId, string name)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.ExecuteNonQuery("UPDATE dbo.Products SET Name = @Name WHERE Id = @ProductId", new { ProductId = productId, Name = name });
}
}

Now that allows you to obtain a connection string however you want in the consuming application.

In a .NET Core app, you might do this to get the connection string from appsettings.json via Microsoft.Extensions.Configuration:

string connectionString = Configuration.GetConnectionString("MyDatabase");
MyDatabaseRepository repository = new MyDatabaseRepository(connectionString);
repository.UpdateProductName(1, "Transformer");

And it still allows you the flexibility to use System.Configuration in your .NET Framework app:

string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
MyDatabaseRepository repository = new MyDatabaseRepository(connectionString);
repository.UpdateProductName(1, "Transformer");

Coupled with Dependency Injection, this becomes a very flexible and powerful tool.

Is using app.config and ConfigurationManager in .NET core advisable?

Some history, the original team to begin shrinking the dependencies included in a .Net application was the Asp.Net team. Microsoft's web framework was bloated compared to more modular frameworks, causing latency in request. According to Scott Hansleman whom frequently tells this joke in presentations:

Who here develops with .Net? Nobody under thirty, fantastic! So how do
we combat this? Become modular, faster, cross platform, and easier to
get started. Otherwise you would go, I want to learn to code.
Download Visual Studio then four hours later write hello world.

So the web team began this transformation, which for the web makes JavaScript Object Notation a better choice than Extended Markup Language. But within a year of the Asp.Net team making these modifications Microsoft restructured their organization for a one .Net. They realized that these changes would cascade across more than just the Asp.Net team. The older project types would not be compatible or work with JavaScript Object Notation, so they transitioned back to Extended Markup for their .csproj and other configuration types. But a lot of developers really liked the JavaScript Object Notation files for settings, they are smaller, clearer, and not as verbose. So Microsoft added the feature back through Microsoft.Extensions.Configuration to allow you the flexibility.

  • The primary purpose was for backwards compatibility.
  • Ensure that it is updated for any .Net Standard application as well.

So you can leverage either. No real benefit, aside from Extended Markup tends to be incredibly tedious to read and verbose compare to a JavaScript Object. JavaScript Object Notation tends to be easier.

appsettings.json and Class libraries that use ConfigurationManager.AppSettings

If you're using .NET Standard 2.0 you can add a reference to the System.Configuration.ConfigurationManager NuGet package to get access to appSettings.

You can add an app.Config file (not web.Config) to your ASP.NET Core project to store the appSettings. This will be copied to the output folder and renamed as AppName.dll.config during the project build.

Is it possible to use .Net Standard System.Configuration.ConfigurationManager.AppSettings with an appSettings.json file

To the best of my knowledge, that functionality is provided by Microsoft.Extensions.Configuration, which is compatible with .NETStandard 2.0.

You can see an example of loading the configuration here:

var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();

This will load an appsettings.json file as well as an environment specific app settings file (ex: appsettings.Production.json).

To get the settings, you can see more about it in the Microsoft Docs.



Related Topics



Leave a reply



Submit