I'm creating a .NET Standard 2.0 library to be consumed from a .NET Framework 4.6.1 application.
This library needs EF Core, but I can't figure out how to read the app.config.
In a .NET Framework library I would initialize my DBContext like this:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
}
But I can't do it since ConfigurationManager is nowhere to be found in .NET Standard 2.0.
How can I read the configuration file from a .NET Standard 2.0 library?
No, class libraries can hold setting files, but their values will be defined in the application configuration (web. config, app.
Add the App. config file to your project. After creating a . NET Framework project, right-click on your project in Solution Explorer and choose Add > New Item. Choose the Application Configuration File item and then select Add.
Create an interface and use dependency inversion for the connection string, so your code will look something like
public interface IConnectionSettings
{
string MyDatabaseConnectionString { get; }
}
class MyClass
{
private readonly IConnectionSettings _connectionSettings;
public MyClass(IConnectionSettings connectionSettings)
{
_connectionSettings = connectionSettings;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionSettings.MyDatabaseConnectionString);
}
}
Then the consuming app running in .NET Framework can then create their own settings implementation and pass it in
public class ConfigurationManagerConnectionSettings : IConnectionSettings
{
public string MyDatabaseConnectionString { get; }
= ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
}
var s = new ConfigurationManagerConnectionSettings();
var myClass = new MyClass(s);
And all the hipster kids can use environment variables:
public class EnvironmentVariableConnectionSettings : IConnectionSettings
{
public string MyDatabaseConnectionString { get; }
= Environment.GetEnvironmentVariable("MyDatabaseConnectionString");
}
Win for everyone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With