Best Practices for using unique connection

Topics: Data Access Application Block
Jan 31, 2012 at 11:45 PM

Could you be more specific about what you are trying to accomplish?  Are you worried about transactions?

Since Enterprise Library 3 there has been support for reusing the same connection within a single transaction.  http://www.davidhayden.com/blog/dave/archive/2007/01/27/TransactionScopeDataAccessApplicationBlock.aspx

You can also get access to the database connection directly but this is not typically done when using Enterprise Library Data Access Application Block:

Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
using (IDbConnection conn = db.CreateConnection())
{
    conn.Open();
    // ....
} 

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Feb 3, 2012 at 2:22 AM

Connection management is done deep within the Database class so it's hard to modify the behavior without creating a new Database implementation and overriding the CreateConnection method (you may also need a custom DbProvider as well).  This answer shows how.

Another option would be to work with the connection directly using ADO but it seems like you want to test using the Enterprise Library code.

Your best bet might be to enable connection pooling and, since this appears to be for a test, set the min and max pool size to 1 which would force the same connection to be used and also set Connection Reset to false. 

I'm just curious what you are trying to accomplish with only having one connection?  

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Oct 31, 2013 at 4:47 AM
You would have to recreate the code from the Enterprise Library (and perhaps also EntLibContrib) source code. Or just directly code in ADO.NET the functionality you need.

For example, you can get a connection, manage its lifetime and then create a command to do whatever you want:
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
using (IDbConnection conn = db.CreateConnection())
{
    conn.Open();
    DbCommand cmd = conn.CreateCommand();
    // ....
} 
~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to