У меня есть кусок кода (.NET Framework 4.5.2, Enterprise Library 5.0.505.0), где мне нужно подключиться к базы данных SQL Server. Однако имя БД может постоянно меняться в зависимости от требований пользователя. Итак, у меня есть следующий фрагмент кода для динамической записи строки подключения в файл 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 во время отладки. Однако, когда я пытаюсь создать объект базы данных, я получаю сообщение об ошибке. Код, используемый для создания объекта БД, приведен ниже.
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) Обновление версии Enterprise Library для 6.0.0.0 решает проблему, но это не вариант для меня. Я должен сохранить его до версии 5.0.505.0.
2) Когда я жестко закодирую строку подключения в файле App.config из руки (вместо того, чтобы записывать ее во время выполнения), приложение работает нормально. Однако я не могу этого сделать в реальной жизни, потому что имя базы данных будет продолжать меняться.
Любая помощь будет очень признательна. Благодаря!