0

我有一段代碼(.NET Framework 4.5.2,Enterprise Library 5.0.505.0),我需要連接到一個SQL Server數據庫。但是,DB名稱可能會根據用戶的要求而不斷變化。所以,我有以下代碼將連接字符串動態寫入app.config文件。嘗試獲取類型爲Database的實例時發生激活錯誤,僅在動態創建連接字符串時發生錯誤

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文件中的連接字符串(而不是在運行時編寫它)時,該應用程序工作正常。但是,我不能在現實生活中這樣做,因爲數據庫名稱會不斷變化。

任何幫助將不勝感激。謝謝!

回答

0

我改變了我的代碼,如下所示,並開始工作。不過,我沒有任何解釋:

public class MyDac 
{ 
    private readonly Database _db; 

    public MyDac() 
    { 
     _db = new SqlDatabase("UserSelectedConnectionString"); 
    } 
} 
相關問題