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.