Browsed by
Category: Design Patterns

C# Unit Of Work Pattern with Dapper

C# Unit Of Work Pattern with Dapper

UPDATE: The code here is based on an existing example on GitHub by Tim Schreiber, you can find the original code here.

At work I’ve started looking into using Dapper instead of Entity Framework. In our case, this is because of performance – we’re on EF 6, not Core (and Dapper is faster still over EF Core even).

I’ve found it really easy to get started with, given there’s very little that Dapper makes you do that you weren’t already if you were using SqlConnection. If you’re used to Entity Framework, you’ll find potentially more work is required to set everything up.

We wanted to get this working with the Unit of Work as our process involved updating half a dozen tables, and if something went wrong we wanted to roll back the changes and report the error.
As always, the code for this post can be found here.
Implementing this pattern will comprise of two parts – the unit of work implementation, and our repositories.

The first thing we’ll do is set up our repository classes, I’ll add two, but as they’re extremely common I’ll only cover one here. If you really want to see both, check out the source code.
I’ve also created entity classes for each of these, but as these are just POCOs there isn’t much point in covering them.
I’ve added a folder called ‘Repositories’ to keep these in, and in there I’ve added two new classes – EmployeeRepository and CustomerRepository.
Each of these has three methods – Add, Update and Remove.
We’ll pass in an IDbTransaction in the constructor of each repository, and from this we can get the connection which we’ll use to execute our SQL queries.
Add and Update take in an entity class representing a record in the table, and Remove simply takes in an int for the id column. Only Add will return anything, the newly set Id of the entity.
All in, this is a simple class:

Since this is more of an example around the Unit of Work pattern, the SQL we’re using is really simple. The main thing to take note of here is the IDbTransaction being passed as a parameter to the Dapper Execute calls.
This does exactly what you’d expect, linking all changes to that transaction, so that if something goes wrong, we can rollback everything in that transaction rather than having to figure anything out for ourselves.
So let’s go ahead and make use of this by implementing the Unit of Work – I’ve done this in a class I’ve called DapperUnitOfWork.
This class will hold our repository – instantiating with the transaction if null, and will include a commit method with attempt to save our changes, and roll back if something goes wrong. I’ve also implemented IDisposable, and in the Dispose method I’m clearing off the IDbTransaction and IDbConnection.
Also worth noting the private ResetRepositories method – this is needed as we instantiate our repository classes with an IDbTransaction. When we’ve committed changes, we’ll be on a new transaction, so we’ll want to re-instantiate our repositories to reflect this.
Your class should look something like this:

No surprises there, it’s easy to see what it’s doing, and it’s easy to use – simply create a new instance of the DapperUnitOfWork class in a using statement, and call the methods on your repository:

Obviously this code could be improved in numerous ways – better error handling, abstraction etc.
But hopefully it’s clear enough to follow!
As always, get in touch if you think there’s a way to improve things 🙂
Or feel free to submit an issue/PR to the repo on Github here.

Introduction to Inversion of Control in C# with Dry IoC

Introduction to Inversion of Control in C# with Dry IoC

Recently I’ve been brushing up on some basic skills, and dependency injection with Inversion of Control is one of those things. Previously when doing this, I’ve stuck to the most commonly used variations of IoC with .NET – Unity and Ninject.
However, after coming across this GitHub example I wanted to give Dry IoC a try given it’s performance benefits over most others.

All this code can be found on my GitHub account here.

The most basic use case of IoC is when you’re resolving an interface to a class implementation. Without IoC, you’d need to know the exact implementation of this interface whenever it’s needed, like so:

Obviously this isn’t ideal as it keeps your code tightly coupled – you don’t want Class A to know about the implementation details of Class B. Avoiding this is where Inversion of Control and Dependency Injection comes in.

When using Dry IoC you can instead register the interface against the implementation when configuring the container:

Now you can then use that container to resolve the interface whenever required, like so:

The same principle also applies when you’re registering a singleton, simply passing the Reuse.Singleton parameter when registering will ensure that the same instance is always returned:

I’ve given this interface a method to change a string on the implementation, and a method to print that string out to the console. This allows you to see that changing the string on the first resolved interface is reflected on the second:

Obviously, this is the most basic usage you can find, so let’s start to dig a little deeper.
The next thing that might be needed is when you have an interface that requires a parameter in the constructor. There are two different ways of doing this depending on whether you’re registering against an implementation that requires a primitive type, or a complex object.
For a primitive type you simply need to specify the parameter when registering the interface by using Made.Of to set up the factory method for the constructor:

While this looks quite complex at first glance, all it’s doing is specifying that when this interface is requested, the constructor should be invoked, and should take the given string as a parameter. This interface then gets resolved as normal when it’s required, and we can print out the parameter to see that this has worked:

Registering with a complex object to be passed in works in much the same way, however it requires that we register an instance of the object with the container:

The code above will register an instance of the TestObject class, giving it the key ‘obj1’ which can then be used to resolve it. Now that this object is available we can register the interface, specifying that this implementation of the object should be used in the constructor:

Again, the sample code on GitHub contains a method that will print out each field so you can see they have been populated. Registering an interface like this could be very useful, for example if you require some configuration settings to be applied that might need to change depending on whether you’re running in Debug or in Production.

This is all well and good, but for the most part when you’re using interfaces you’ll have multiple different implementations. In this case you need to be able to retrieve the specific implementation you want, or perhaps in some cases retrieve all registered implementations of the interface, so let’s take a look at those.

Registering multiple implementations to the container is easy – simply register them as normal, but pass a key when doing so that can later be used to retrieve it. The key is an object type – I’ve used an enum as an easy way to keep track of them:

Now they’ve been registered, they can be resolved easily enough again, just by specifying the key you registered them against:

If you’re wanting to resolve all implementations of the interface you can do so into an IEnumerable by using ResolveMany instead of Resolve:

Again, the sample code on GitHub includes Print methods on these implementations so that you can see the correct classes are being resolved.

I hope this has given a good basic introduction to Inversion of Control with C# and Dry IoC. In a future post I’ll expand on this and show how you can use IoC and Dependency Injection to help you follow the principles of TDD.

Link to the code on GitHub can be found here.