Encapsulate a database connection in business objects or not?

I usually like to create a database connection myself and manually control its lifetime using `using {} '. For example:

SqlConnection sqlConnection = new SqlConnection( connectionString );
using( sqlConnection ) {
    BusinessObject myBusinessObject = new BusinessObject( sqlConnection );
    // do stuff with the business object
    ...
}

Thus, it is visible and obvious that I am using a resource that needs to be cleaned accordingly. However, this leads to many repetitive efforts. I am tempted to create an Sql connection inside a business object and implement IDisposable on it. I would close the connection in the Dispose () method.

using( BusinessObject myBusinessObject = new BusinessObject() ) {
    // do stuff with myBusinessObject
    ...
}

The problem I am facing is that it may not be so obvious that the business object should be deleted if you do not see it in use.

How do you guys do this?

+3
3

- ( ) . - ( ), , - , -. , . @Marc , Unit of Work, .

, LINQtoSQL, nHibernate, Subsonic .., , , , , . , , .

+4

, .

-, , - (.. ). , (- ) . , .

- , TransactionScope , db.

+3

I do not think that a business object should know or care about whether it is permanent. An individual, permanent business entity cannot know when it is part of a larger unit of work; that the responsibility for the service level. Leave the connection to business objects. The service level is the right place to receive connections, usually from a connection pool, set transaction boundaries, commit or rollback, and clean up.

0
source

Source: https://habr.com/ru/post/1705500/


All Articles