cofoundry-cms / cofoundry

Cofoundry is an extensible and flexible .NET Core CMS & application framework focusing on code first development

Home Page:https://www.cofoundry.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to get DB connection and transation

JornWildt opened this issue · comments

Sorry to bother you again ... I am trying to incorporate Rebus messaging in Cofoundry and I want to enlist message output from Rebus with the current connection+transaction of Cofoundry.

Using SQL server as the transport medium for Rebus, I have two possibilities - but here I will focus on using Rebus' Outbox pattern.

The idea is that Rebus drops its outgoing messages in a database table from the same database as Cofoundry using the same database transaction. If anything fails, both my business data as well as messages will be rolled back - or committed together if it succedes.

For this to work, I need to get my hands on the inner database connection and transaction from Cofoundry.

Example:

public async Task ExecuteAsync(RegisterNewSignUpRequestCommand cmd, IExecutionContext executionContext)
{
  using (var scope = _advancedContentRepository.Transactions().CreateScope())
  using (var rebus_scope = new RebusTransactionScope())
  {
    Microsoft.Data.SqlClient.SqlConnection connection = ... what here ...;
    Microsoft.Data.SqlClient.SqlTransaction transaction = ... what here ...;
    rebus_scope.UseOutbox(connection, transaction);
  }
}

Do you have any idea of how to get the connection and transation (from the Microsoft.Data.SqlClient namespace)?

To get the connection you can use ICofoundryDbConnectionManager.GetShared() to get the Cofoundry DbConnection. Not sure about the transaction offhand, the Cofoundry transaction manager is just deferring to System.Transactions.TransactionScope, which usually just takes care of the underlying transaction - does rebus require the transaction explicitly?

You could get both from CofoundryDbContext if you request it from the DI container, but I wouldn't encourage you to use that directly.

Thanks. I found that the DbContext class can be used to get the connect and then the SqlConnection:

        System.Data.Common.DbConnection db =  _dataContext.Database.GetDbConnection();
        
        Microsoft.Data.SqlClient.SqlConnection connection = (Microsoft.Data.SqlClient.SqlConnection)db;
        Microsoft.Data.SqlClient.SqlTransaction transaction = ... still missing ...;
        rebus_scope.UseOutbox(connection, transaction);

But Rebus requires a real SqlTransaction - not a transaction scope. This has nothing to do with Cofoundry, so I'll close it here and see if Rebus can help me.