Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transaction scope instead of DB transaction #11

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,11 @@ public class CommunicationDataAccessModule : Module
{
public override void Load(IServiceCollection services)
{
services.AddDbContext<CommunicationDbContext>((sp, bld) =>
services.AddDbContext<ICommunicationDbContext, CommunicationDbContext>((sp, bld) =>
{
var factory = sp.GetRequiredService<IConnectionFactory>();
bld.UseSqlServer(factory.GetConnection());
});

services.AddScoped<ICommunicationDbContext>(sp =>
{
var context = sp.GetRequiredService<CommunicationDbContext>();
var connectionFactory = sp.GetRequiredService<IConnectionFactory>();

context.Database.UseTransaction(connectionFactory.GetTransaction());

return context;
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ public ConnectionFactory(string connectionString)
}

private DbConnection _connection;
private DbTransaction _transaction;
private readonly string _connectionString;

public DbConnection GetConnection()
Expand All @@ -25,18 +24,10 @@ public DbConnection GetConnection()
return _connection;
}

public DbTransaction GetTransaction()
{
return _transaction ??= GetConnection().BeginTransaction();
}

public bool IsConnectionOpened => _connection != null;

public bool IsTransactionStarted => _transaction != null;

public void Dispose()
{
_transaction?.Dispose();
_connection?.Dispose();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ namespace Shop.Framework.UseCases.Interfaces.Services
public interface IConnectionFactory : IDisposable
{
DbConnection GetConnection();
DbTransaction GetTransaction();
bool IsConnectionOpened { get; }
bool IsTransactionStarted { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,11 @@ public class OrderDataAccessModule : Module
{
public override void Load(IServiceCollection services)
{
services.AddDbContext<OrderDbContext>((sp, bld) =>
services.AddDbContext<IOrderDbContext, OrderDbContext>((sp, bld) =>
{
var factory = sp.GetRequiredService<IConnectionFactory>();
bld.UseSqlServer(factory.GetConnection());
});

services.AddScoped<IOrderDbContext>(sp =>
{
var context = sp.GetRequiredService<OrderDbContext>();
var connectionFactory = sp.GetRequiredService<IConnectionFactory>();

context.Database.UseTransaction(connectionFactory.GetTransaction());

return context;
});
}
}
}
18 changes: 13 additions & 5 deletions ModularMonolith/Shop.Tests.Unit/WorkflowTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Shop.Communication.UseCases;
using Shop.Emails.Implementation;
using Shop.Framework.UseCases.Implementation;
using Shop.Framework.UseCases.Interfaces.Services;
using Shop.Order.Contract.Implementation;
using Shop.Order.DataAccess.MsSql;
using Shop.Order.UseCases;
Expand All @@ -37,7 +38,7 @@ public async Task Should_Create_Order_And_Email()
var (connectionString, configuration) = CreateConfiguration();

var services = CreateServiceProvider(configuration);

services.RegisterModule<CommunicationDataAccessModule>(configuration);
var serviceProvider = services.BuildServiceProvider();

var (orderDbContext, communicationDbContext) = await CreateDatabase(connectionString);
Expand Down Expand Up @@ -65,7 +66,15 @@ public async Task Should_Not_Create_Order_And_Email_On_Error()
var (connectionString, configuration) = CreateConfiguration();

var services = CreateServiceProvider(configuration);
services.Decorate<ICommunicationDbContext, TestCommunicationDbContext>();
//TODO Decorator doesn't work
//services.RegisterModule<CommunicationDataAccessModule>(configuration);
//services.Decorate<ICommunicationDbContext, TestCommunicationDbContext>();
services.AddDbContext<CommunicationDbContext>((sp, bld) =>
{
var factory = sp.GetRequiredService<IConnectionFactory>();
bld.UseSqlServer(factory.GetConnection());
});
services.AddScoped<ICommunicationDbContext, TestCommunicationDbContext>();

var serviceProvider = services.BuildServiceProvider();

Expand All @@ -91,7 +100,7 @@ class TestCommunicationDbContext : ICommunicationDbContext
{
private readonly ICommunicationDbContext _context;

public TestCommunicationDbContext(ICommunicationDbContext context)
public TestCommunicationDbContext(CommunicationDbContext context)
{
_context = context;
}
Expand Down Expand Up @@ -140,9 +149,8 @@ private ServiceCollection CreateServiceProvider(IConfiguration configuration)
services.AddMediatR(assemblies);
services.AddAutoMapper(assemblies);

services.AddScoped(typeof(IPipelineBehavior<,>), typeof(DbTransactionPipelineBehavior<,>));
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TransactionScopePipelineBehavior<,>));

services.RegisterModule<CommunicationDataAccessModule>(configuration);
services.RegisterModule<OrderDataAccessModule>(configuration);

services.RegisterModule<FrameworkModule>(configuration);
Expand Down
3 changes: 2 additions & 1 deletion ModularMonolith/Shop.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
Expand Down Expand Up @@ -53,7 +54,7 @@ public void ConfigureServices(IServiceCollection services)
services.RegisterModule<OrderContractModule>(Configuration);
services.RegisterModule<OrderUseCasesModule>(Configuration);

services.AddScoped(typeof(IPipelineBehavior<,>), typeof(DbTransactionPipelineBehavior<,>));
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TransactionScopePipelineBehavior<,>));

var location = Assembly.GetExecutingAssembly().Location;
var assemblies = Directory.EnumerateFiles(Path.GetDirectoryName(location), "Shop*UseCases.dll")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,38 @@
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using MediatR;
using Shop.Framework.UseCases.Interfaces.Services;
using Shop.Framework.UseCases.Interfaces.Transactions;

namespace Shop.Web.Utils
{
public class DbTransactionPipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
public class TransactionScopePipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>, ITransactionalRequest
{
private readonly IConnectionFactory _connectionFactory;

public DbTransactionPipelineBehavior(IConnectionFactory connectionFactory)
public TransactionScopePipelineBehavior(IConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}

public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
if (_connectionFactory.IsTransactionStarted)
if (_connectionFactory.IsConnectionOpened)
{
return await next();
}

await using var connection = _connectionFactory.GetConnection();
await using var transaction = _connectionFactory.GetTransaction();
using var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },
TransactionScopeAsyncFlowOption.Enabled);

await using var connection = _connectionFactory.GetConnection();

var result = await next();

await transaction.CommitAsync(cancellationToken);
scope.Complete();

return result;
}
Expand Down