Okay, it's been half a decade since the OP asked, but as I keep coming across this question when I develop with Dapper (or anything really, this isn't really very Dapper specific). Here's my two cents.
First Let's talk about the other answers:
pimbrouwers' answer IDbContext
manages Unit of Work in a very similar way to how entity framework does it. It's perfectly sensible and easy to understand. But the major drawback is that you end up passing a IDbContext
to all your business code. It's a bit of a god object. Just like in EF. I prefer to inject individual repositories and make it explicit what database stuff I'm going to be doing, instead of having everything in my domain model always just one .
away. However, if you don't agree with my 'god object' objection, pim's answer sounds like the right one for you.
Amit Joshi's answer has the MyRepository
take the unit of work as a constructor parameter. This means you can't inject Repositories anymore. This can be solved by injecting repository factories instead, but this is certainly its own level of hassle.
A quick aside: In some of these answers the word "transaction" and "unit of work" are used interchangeably. In practice here they have a 1:1 relationship, but they aren't the same thing. The "transaction" is the db implementation, the "unit of work" is more of a higher level conceptual thing. If we had more persistence that just one database, there would be a difference, and the UOW would contain more than just one transaction. So, to avoid confusion, "Transaction" is probably not a great word to use in our UOW interface.
So here's my way:
I'll start with the Usage
// Business code. I'm going to write a method, but a class with dependencies is more realistic
static async Task MyBusinessCode(IUnitOfWorkContext context, EntityRepoitory repo)
{
var expectedEntity = new Entity {Id = null, Value = 10};
using (var uow = context.Create())
{
expectedEntity.Id = await repo.CreateAsync(expectedEntity.Value);
await uow.CommitAsync();
}
using (context.Create())
{
var entity = await repo.GetOrDefaultAsync(expectedEntity.Id.Value);
entity.Should().NotBeNull();
entity.Value.Should().Be(expectedEntity.Value);
}
}
The unit of work just wraps a transaction and is shortlived:
public class UnitOfWork : IDisposable
{
private readonly SQLiteTransaction _transaction;
public SQLiteConnection Connection { get; }
public bool IsDisposed { get; private set; } = false;
public UnitOfWork(SQLiteConnection connection)
{
Connection = connection;
_transaction = Connection.BeginTransaction();
}
public async Task RollBackAsync()
{
await _transaction.RollbackAsync();
}
public async Task CommitAsync()
{
await _transaction.CommitAsync();
}
public void Dispose()
{
_transaction?.Dispose();
IsDisposed = true;
}
}
The Context is more interesting. It's the way in which the repos and the unit of works communicate behind the scenes.
There's one interface for the business code to manage a unit of work, and one for the repo to abide by that unit of work.
public class UnitOfWorkContext : IUnitOfWorkContext, IConnectionContext
{
private readonly SQLiteConnection _connection;
private UnitOfWork _unitOfWork;
private bool IsUnitOfWorkOpen => !(_unitOfWork == null || _unitOfWork.IsDisposed);
public UnitOfWorkContext(SQLiteConnection connection)
{
_connection = connection;
}
public SQLiteConnection GetConnection()
{
if (!IsUnitOfWorkOpen)
{
throw new InvalidOperationException(
"There is not current unit of work from which to get a connection. Call BeginTransaction first");
}
return _unitOfWork.Connection;
}
public UnitOfWork Create()
{
if (IsUnitOfWorkOpen)
{
throw new InvalidOperationException(
"Cannot begin a transaction before the unit of work from the last one is disposed");
}
_unitOfWork = new UnitOfWork(_connection);
return _unitOfWork;
}
}
public interface IConnectionContext
{
SQLiteConnection GetConnection();
}
public interface IUnitOfWorkContext
{
UnitOfWork Create();
}
Here's how the repo does that:
public class EntityRepository
{
private readonly IConnectionContext _context;
public EntityRepository(IConnectionContext context)
{
_context = context;
}
public async Task<int> CreateAsync(int value)
{
return await _context.GetConnection().QuerySingleAsync<int>(
@"
insert into Entity (Value) values (@value);
select last_insert_rowid();
", new { value });
}
public async Task<Entity> GetOrDefaultAsync(int id)
{
return await _context.GetConnection().QuerySingleOrDefaultAsync<Entity>(
@"
select * from Entity where Id = @id
", new { id });
}
}
And finally here's DI. Do the setup. Here's a single threaded console application Example. I imagine it would be sensible to make it a singleton or per request. The implementation of UnitOfWorkContext can be changed to match your threading choices anyway (Eg by using a UnitOfWorkContext with a thread static UOW).
public static void Main(string[] args)
{
using (var connection = new SQLiteConnection("Data Source=:memory:"))
{
connection.Open();
Setup(connection);
var context = new UnitOfWorkContextContext(connection);
var repo = new EntityRepository(context);
MyBusinessCode(repo, context).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
Full version on Github: https://github.com/NathanLBCooper/unit-of-work-example
Analysis:
We've eliminated god objects and don't need to create factories for all our repositories. the cost is that we've got a little bit more of a subtle non-obvious link between our repos and the Unit of Work stuff. There's no boiler plate, but we do need to be careful about what lifetime we give our context object, especially when multithreading.
I think this is a trade-off that's worth it, but that's me.
PS
I'll add one thing. Maybe you've looked up this answer because you've started using dapper. Right now all your repository methods are separate atomic operations and you feel no need to combine them into transactions yet. Then for the time being you don't need to do any of this. Close this browser window, write your repositories in the most simple and obvious way and be happy.