正如我所说,您不应该直接依赖于如何在类库中获取配置。保持你的类库灵活。
不要在你的类库中这样做:
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 });
}
}
通过在您的类库中直接使用 ConfigurationManager,您已将该类绑定到只允许一种形式的获取连接字符串。这意味着如果您想使用 appsettings.json、环境变量、KeyVault 或任何其他获取配置的方法,则不能。
相反,这样做:
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 });
}
}
现在,您可以根据需要在消费应用程序中获取连接字符串。
在 .NET Core 应用中,您可以通过 Microsoft.Extensions.Configuration 从 appsettings.json 获取连接字符串:
string connectionString = Configuration.GetConnectionString("MyDatabase");
MyDatabaseRepository repository = new MyDatabaseRepository(connectionString);
repository.UpdateProductName(1, "Transformer");
它仍然允许您在 .NET Framework 应用程序中灵活地使用 System.Configuration:
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
MyDatabaseRepository repository = new MyDatabaseRepository(connectionString);
repository.UpdateProductName(1, "Transformer");
再加上Dependency Injection,这将成为一个非常灵活和强大的工具。