4

I have a Oracle database and I'm using the Oracle.ManagedDataAccess.

In some cases I will need to do actions in a single transactions, but often not.

I'm not sure what the best way to handle DbConnection objects within a single TransactionScope.

I could inject a DbConnection into the repositories and then even use LifetimePerScope to ensure they all get the same DbConnection instance. But is that a smart move, is it ok to .Open() the connection once.

using (var scope = _lifetimeScope.BeginLifetimeScope())
{
    var connection = scope.Resolve<IDbConnection>();
    var personRepo = scope.Resolve<IPersonRepository>();
    var workRepo = scope.Resolve<IWorkRepository>();
    connection.Open();
    var transaction = connection.BeginTransaction()
    personRepo.DeleteById(someId);
    workRepo.DeleteByPersonId(someId);
    transaction.Commit();
}

This would force me to always use a LifetimeScope, even if not using a Transaction, and open the connection outside the repository method.

Are TransactionScopes dependent on a single connection or can I open multiple connections (how does the connectionPool handle that while a transaction is open?) within the same transaction?

I'm a total outsider to DbConnections and all that so I might be totally misunderstanding the best way to use TransactionScope and DbConnections.

4

2 回答 2

3

可能重复:为什么总是关闭数据库连接?

由于这有赏金,我不能将其标记为重复:(

无论如何,连接池在很大程度上是为您完成的。您应该尽快关闭连接,以将它们返回到池中。

事务与特定打开的连接相关,应在关闭连接时完成。

于 2015-09-10T11:59:51.993 回答
2

与 BeginTransaction() 相关的 TransactionScope 特定于连接。如果要跨多个连接(多个 DB、资源)维护事务,则需要DTC感知TransactionScope。这是一个类似的SO 帖子。您需要使用它Oracle.ManagedDataAccessDTC.dll来促进这一点。

您可能需要浏览这些链接:

1.关于transactionscope

2.如何配置 DTC 以支持 Oracle 事务

希望这可以帮助。

于 2015-09-17T09:37:01.330 回答