尝试获取数据库类型的实例时发生激活错误,仅在动态创建连接字符串时发生错误

Activation error occured while trying to get instance of type Database, error occurring only when connection string is created dynamically

我有一段代码(.NET Framework 4.5.2,Enterprise Library 5.0.505.0)需要连接到 SQL 服务器数据库。但是,数据库名称可能会根据用户的要求不断变化。因此,我有以下代码将连接字符串动态写入 app.config 文件。

public void CreateNewConnectionStringInConfig(string initialCatalog)
{
      SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
      builder.DataSource = ConfigurationManager.AppSettings["Data Source"];
      builder.PersistSecurityInfo = true;
      builder.InitialCatalog = initialCatalog; //This is the DB name
      builder.UserID = ConfigurationManager.AppSettings["User ID"];
      builder.Password = ConfigurationManager.AppSettings["Password"];

      // Get the application configuration file.
      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

      // Create a connection string element.
      ConnectionStringSettings csSettings = new ConnectionStringSettings("UserSelectedConnectionString", builder.ConnectionString, "System.Data.SqlClient");

      // Get the connection strings section.
      ConnectionStringsSection csSection = config.ConnectionStrings;

      // Add the new element.
      csSection.ConnectionStrings.Add(csSettings);

      // Save the configuration file.
      config.Save(ConfigurationSaveMode.Modified);

     // Refresh the section so the new configuration can be re-read
      ConfigurationManager.RefreshSection("connectionStrings");

}

我检查过,调试时在 vshost.exe.Config 文件中创建的连接字符串正常。但是,当我尝试创建数据库对象时,出现错误。用于创建DB对象的代码如下所示。

public class MyDac
{
    private readonly Database _db;

    public MyDac()
    {
        DatabaseProviderFactory factory = new DatabaseProviderFactory();
        _db = factory.Create("UserSelectedConnectionString");
    }
}

我在尝试创建 _db 对象时遇到以下错误。

Activation error occured while trying to get instance of type Database, key "UserSelectedConnectionString"

Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type Database, key "UserSelectedConnectionString" --->     Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Data.Database", name = "UserSelectedConnectionString".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Database does not have an accessible constructor.

我尝试过的东西:

1) 将企业库版本升级到 6.0.0.0 可以解决问题,但这对我来说不是一个选项。我必须保持它到版本 5.0.505.0.

2) 当我事先在 App.config 文件中硬编码连接字符串(而不是在 运行 期间写入)时,应用程序运行良好。但是,我不能在现实生活中这样做,因为数据库名称会不断变化。

任何帮助将不胜感激。谢谢!

我如下所示更改了我的代码并开始工作。但是,我对此没有任何解释:

public class MyDac
{
    private readonly Database _db;

    public MyDac()
    {
        _db = new SqlDatabase("UserSelectedConnectionString");
    }
}