Hello,
We are looking into the samples on setting up Outbox with EF Core. Our situation is slightly different in the sense that we prefer using the AddDbContext-method from EF Core. In addition, the creation of the context is not in our solution but in an external package. Which is why we devised a setup like this:
public ContextWrapper RegisterWrapperScoped(IServiceProvider serviceprovider)
{
var session = serviceprovider.GetRequiredService<ISqlStorageSession>();
var context = serviceprovider.GetRequiredService<ReceiverDataContext>();
// context.Database.SetDbConnection(session.Connection); - possible fix
context.Database.UseTransaction(session.Transaction);
session.OnSaveChanges((s, token) => context.SaveChangesAsync(token));
return new ContextWrapper(context);
}
This method would be called when creating our IServiceCollection container (we are using the externally managed mode).
Problem:
Our problem is that we are getting an exception when calling this line:
context.Database.UseTransaction(session.Transaction);
This line causes the following exception:
System.InvalidOperationException: âThe specified transaction is not associated with the current connection. Only transactions associated with the current connection may be used.â
We know that we can resolve this problem by calling the following before .UseTransaction
:
context.Database.SetDbConnection(session .Connection);
However, this does raise doubts on the cleanliness of the code. Are there any samples (e.g. by Particular) on how we can properly have the DbContext use the same transaction as the ISqlStorageSession when using the AddDbContext-method from Microsoftâs EF Core?
Additional info on the exception
context.Database.GetConnectionString() == session .Connection.ConnectionString
istrue
context.Database.GetDbConnection() == session .Connection
isfalse
session.Connection == sqlStorageSession.Transaction.Connection
istrue
- the objectId-property in the SqlConnections differ between the session and the dbContext, so it appears that we may need to use the same connection when initializing the session and context.
- we are using EntityFramework Core (version 6)
If there are any suggestions or questions, weâd love to hear it!