Skip to content

Commit

Permalink
Showing 3 changed files with 34 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -254,7 +254,7 @@ ReceiveResult TryReceiveWithNativeTransaction()

try
{
UnitOfWork.SetTransaction(connection.ConnectionString, transaction);
UnitOfWork.SetTransaction(transaction, connection.ConnectionString);

if (tryProcessMessage(message))
{
2 changes: 1 addition & 1 deletion src/NServiceBus.SqlServer/SqlServerTransport.cs
Original file line number Diff line number Diff line change
@@ -37,7 +37,7 @@ public override void Initialize()
.ConnectionStrings
.Cast<ConnectionStringSettings>()
.Where(x => x.Name.StartsWith("NServiceBus/Transport/"))
.ToDictionary<ConnectionStringSettings, string, string>(x => x.Name.Replace("NServiceBus/Transport/", String.Empty), y => y.ConnectionString);
.ToDictionary(x => x.Name.Replace("NServiceBus/Transport/", String.Empty), y => y.ConnectionString);

if (String.IsNullOrEmpty(defaultConnectionString))
{
34 changes: 32 additions & 2 deletions src/NServiceBus.SqlServer/UnitOfWork.cs
Original file line number Diff line number Diff line change
@@ -4,9 +4,20 @@
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading;
using Settings;

public class UnitOfWork : IDisposable
{
public UnitOfWork()
{
defaultConnectionString = SettingsHolder.Get<string>("NServiceBus.Transport.ConnectionString");
}

public SqlTransaction Transaction
{
get { return GetTransaction(defaultConnectionString); }
}

public void Dispose()
{
//Injected
@@ -17,25 +28,44 @@ public SqlTransaction GetTransaction(string connectionString)
return currentTransactions.Value[connectionString];
}

public void SetTransaction(string connectionString, SqlTransaction transaction)
public void SetTransaction(SqlTransaction transaction)
{
SetTransaction(transaction, defaultConnectionString);
}

public void SetTransaction(SqlTransaction transaction, string connectionString)
{
if (currentTransactions.Value.ContainsKey(connectionString))
{
throw new InvalidOperationException("Transaction already exists for connection");
}

currentTransactions.Value.Add(connectionString, transaction);
}

public bool HasActiveTransaction()
{
return HasActiveTransaction(defaultConnectionString);
}

public bool HasActiveTransaction(string connectionString)
{
return currentTransactions.Value.ContainsKey(connectionString);
}


public void ClearTransaction()
{
ClearTransaction(defaultConnectionString);
}

public void ClearTransaction(string connectionString)
{
currentTransactions.Value.Remove(connectionString);
}

readonly ThreadLocal<Dictionary<string, SqlTransaction>> currentTransactions
= new ThreadLocal<Dictionary<string, SqlTransaction>>(() => new Dictionary<string, SqlTransaction>(StringComparer.InvariantCultureIgnoreCase));

string defaultConnectionString;
}
}

0 comments on commit c4c0711

Please sign in to comment.