Skip to content

Instantly share code, notes, and snippets.

@mpetrinidev
Last active December 4, 2019 11:44
Show Gist options
  • Save mpetrinidev/17440f10f0f9f87de76ce714a031a65c to your computer and use it in GitHub Desktop.
Save mpetrinidev/17440f10f0f9f87de76ce714a031a65c to your computer and use it in GitHub Desktop.
Dapper + MediatR
public class Service1 : IService1
{
private readonly IDbConnection _connection;
private readonly IDbTransaction _transaction;
public Service1(IDbConnection connection, IDbTransaction transaction)
{
_connection = connection;
_transaction = transaction;
}
public async Task CallDatabase()
{
await _connection.QueryAsync("", transaction: _transaction);
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IService1, Service1>();
services.AddTransient<IDbConnection>(provider => new SqlConnection(""));
services.AddScoped(provider => provider.GetService<IDbConnection>().BeginTransaction());
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TransactionBehavior<,>));
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IDbTransaction _transaction;
public TransactionBehavior(IDbTransaction transaction)
{
_transaction = transaction;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var response = default(TResponse);
try
{
response = await next();
_transaction.Commit();
}
catch (Exception e)
{
_transaction.Rollback();
}
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment