Data Access Application Block: Assigning a connection string at runtime

Topics: Data Access Application Block
Mar 29, 2007 at 1:59 AM
Enterprise Library: June 2005 Release for .NET v1.1

My application is going to be hosted by my client and I need to be able to assign a connection string at runtime. The connection string will be obtained from a custom class in an external assembly that has been developed by my client.

I have been able to figure out to set the connection string at runtime as use code similar to this:
Database database = DatabaseFactory.CreateDatabase();
IDBConnection connection = database.GetConnection();
connection.ConnectionString = someStoredConnectionString;

The problem I am running in to is that when my test application loads, an exception is thrown because System.Security.Policy.PolicyException: Required permissions cannot be acquired. If I put valid connection information in to my configuraiton file for the data access application block the test programs run fine. I get the exception at application start (my has not attempted to do anything yet) if the configuation file contains invalid connection information or the information is missing.

Is there a way to way to use the current version of the data access application block the same was as in a previous version? For example:
SqlReader reader = SqlHelper.ExecuteReader(someConnectionString, someStoredProcedureName);
Mar 29, 2007 at 4:26 PM
In Ent Lib 2.0 and 3.0 you can do something like this:

public static class SqlDatabaseFactory
    private static readonly string _connectionString = @"Data Source=...";
    public static Database CreateDefault()
        return Create(_connectionString);
    public static Database Create(string connectionString)
        return new SqlDatabase(connectionString);

where you can directly create the SqlDatabase Class that is responsible for communicating with a SQL Server Database. I put it behind a Factory Method just to abstract out the class a bit.

In your application you can now just create the Database Class like this to use a default connection string

    Database database = SqlDatabaseFactory.CreateDefault();

or pass it the connection string

    Database database = SqlDatabaseFactory.Create("Data Source=...");

I assume the same is possible with Ent Lib 1.1, but I don't have it on my PC to test.




David Hayden
Microsoft MVP C#