This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work your way through!

Part 1 – The What/Why/Who
Part 2 – Dapper Query Basics
Part 3 – Updates/Inserts/Deletes
Part 4 – Dapper Contrib


What Is Dapper Contrib?

Dapper.Contrib is a “helper” library built on top of Dapper, that adds a couple of “quality of life” enhancements to otherwise annoying Dapper hurdles. Most notably, updates and inserts become much simpler with Dapper.Contrib. So let’s jump right in!

Installing Dapper.Contrib

From your Package Manager console window you can install the Dapper.Contrib package.

If you haven’t already installed Dapper, this will drag Dapper in as a dependency too! Note that at times you do have to do a juggle with versions of Dapper if you install it first, then Contrib second. The easiest way if you really want to use Contrib is remove the direct reference to the Dapper nuget, and simply install Contrib and let it drag in the version it needs.

Model Our C# Class For Writes In Dapper.Contrib

The important thing when using Dapper.Contrib is that you need a C# model to match that of your database model. Again I can’t stress enough that this should really only be used in the case of writes. When reading data, the entire point of using Dapper is that you don’t over-select and so you should attempt to use applicable DTO’s whenever possible.

From earlier, we have our C# model ready to go :

This works as is, but there are a couple of things to note.

Firstly, Dapper.Contrib requires an “Id” to be able to update a record. In our case, we have a property called “Id” and Dapper.Contrib uses this convention and knows it’s our primary key on our table. But what if we use something like “EventId” as our primary key? That’s easy too.

We just add the “Key” attribute from our Dapper.Contrib library to tell it that’s our primary key.

Next, we are also required that the class name be the same as the SQL Table name, but as a plural. So in our case, our class name is Event and it expects that our database table be called “Events”.  So how can we say nope, we want to stick with the singular?

Again, another attribute. There is actually a couple more attributes that do come in handy, but these are the main ones you should know right off the bat.

Inserting Records Using Dapper.Contrib

This should hopefully make things easier.

… Pretty awesome right! So we are back to having this nice “Insert” method that takes our object and creates an insert statement. It takes some of that perfect control away from us, but when it comes to inserts there isn’t much that we would want to be careful of when it comes to generating the insert statement so I’m happy with it.

Get A Record By Id Using Dapper.Contrib

Contrib also has this nifty feature where it can get a full record by Id. I feel like this sort of strays a little from the intention of Dapper because you should be trying to avoid doing a “SELECT *” and instead only get what you need. But we’ll use it later so I wanted to show it off.

Because it knows we are requesting a type of “Event”, it knows what table that’s from and grabs us the entire object based on it’s primary key Id.

Updating Records Using Dapper.Contrib

Contrib can also do updates. Although they are a little less slick.

First off, we can obviously get our object by ID, update it, then write it like so :

So Contrib has given us that handy “Update” method. But the problem is when we check the actual SQL that got run :

So it basically updated all fields even if they weren’t touched. Because of this we have to get the record by Id before updating because we need to make sure all other fields (Not just the one we want to update) are set correctly.

Now Dapper.Contrib does have dirty tracking, but IMO that’s just as pointless as you still need to get the full object by ID in the first place to do entity tracking, and the entire point is that we aren’t overselecting.

In my opinion, Updates are still a good candidate for doing custom SQL instead of using Contrib, but that’s just my personal feeling!

Delete Records Using Dapper.Contrib

Deleting is actually fairly simple. As long as Dapper.Contrib knows what your primary key is, it can delete records based on that.

To be honest, this syntax annoys me somewhat as we are creating an object for no reason! Wouldn’t it just be easier to pass in a simple Int parameter?

What’s Next?

That’s actually it! We could get into the nitty gritty of Dapper, or even explore some of the other Dapper extension libraries such as Dapper.Rainbow or DapperExtensions, but they are largerly the same as Dapper.Contrib with minor differences. They are definitely worth investigating however!

Feel free to drop a comment below on your thoughts on Dapper and what project’s you’ve used it on in the past, I’d love to hear them!

This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work your way through!

Part 1 – The What/Why/Who
Part 2 – Dapper Query Basics
Part 3 – Updates/Inserts/Deletes
Part 4 – Dapper Contrib


Updating A Record

So.. Here’s where things with Dapper get kinda rough. You see, to update a record we use the “Execute” method from Dapper like so :

And of course you can use parameters with the execute statement also. So we could change that to look like :

I mean yeah, it works but… It’s kinda rough right? Imagine if we wanted to update multiple fields at once how unweildy this statement might get. But then again, maybe that’s good. We are only updating exactly what we want to update and nothing more.

It’s sort of a “Great power comes great responsibility” type issue.

Inserting A Record

If you thought updating a record was rough, wait till you see inserting.

Again… It’s pretty basic. Infact all dapper is really doing is executing our insert statement, but we are kinda doing all the leg work here. Similar to updating, we can use parameters here to clean the values up a bit, but it’s still a lot of manual work. Obviously each time we create a new column, we need to come back to this statement and make sure it works as we intend it to.

Delete A Record

No big surprises here.

The execute method kinda becomes our catch all for “Execute this statement and don’t worry about the result”.

How About CQRS?

It’s pretty common for CQRS to be a hot topic when talking about Dapper. After all, we’ve kind of seen that while reading data in Dapper is super powerful, slick, and easy. Writing feels cumbersome. For this reason I’ve found myself using doing writes using a different ORM (EF or NHibernate), but sticking with Dapper for querying. It works, but it’s not required (As we will soon see!).

What’s Next?

So updating and inserting records is a bit oof. But there is an extension library for Dapper called Dapper.Contrib that actually makes this super simple. Let’s take a look at that!

This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work your way through!

Part 1 – The What/Why/Who
Part 2 – Dapper Query Basics
Part 3 – Updates/Inserts/Deletes
Part 4 – Dapper Contrib


Installing Dapper

Dapper is a nuget package that does nothing more than “augment” the existing SQLConnection object in .NET Core….. Reading that line back I’m not sure it makes sense but hopefully it will at the end. In simple terms you can install the Dapper nuget package by running the following from your Package Manager Console.

In the following examples I’m just running them from a simple console application, but you can install Dapper into any type of .NET Full Framework/.NET Core application.

Follow Along Data

For much of this tutorial, I’m going to be using some data that I created for a simple “Event” database. There really isn’t much to it, but if you want to follow along at home you can grab the script to create the database/tables/data from this Github Gist here : https://gist.github.com/mindingdata/00c2d608c4a0b4ea22e76e95c1d1417e

It’s not required and for the most part everything we do here will be super simple. But if you want to write the queries in your own console application as we go, that’s cool too!

Creating A Database Connection

As you might have seen earlier, when using Dapper we have to create our own SQL Connection to the database. Dapper doesn’t do this for us. But.. It’s simple enough. For example in a console application that I’ve already installed Dapper from Nuget in, all it takes is :

That’s it! We now have a connection to our database that is “Dapper” ready. You’ll also notice that at this point, the only “Using” statement we would actually be using is using System.Data.SqlClient; . That’s because the SqlConnection object is the regular one from the .NET library, so far we haven’t even used Dapper yet!

Query A Single Row

Let’s add some magic and actually get the above SQL Connection actually doing something. In my example database, I have a table called “Event” that has a list of events in it. I want to know specifically what the name of the event is with the Id of 1.

… That’s it. We can of course write our initial SQL in something like SQL Management Studio, and then copy it across. We have complete control over the query and it’s going to run *exactly* what we told it to.

The actual magic part of this is the “QueryFirst” method on our connection. If we jump into the source code of Dapper we can see this is just an extention method on the SqlConnection object.

That’s part of the beauty of Dapper. It’s using really simple concepts that we already know like SqlConnection, and extending them just a little bit more to be useful.

Query A Table Into An Object

So far we are just returning a single property, a string. That’s not that amazing really. But what if we wanted the full Event object instead. Well… Dapper handles that out of the box too.

First we create a class that maps to our SQL Table :

Then we modify our statement a bit to instead be a SELECT * and instead use the return type of Event instead of string. So it looks like so :

If you’ve ever used raw ADO statements before in .NET, you’ll know the pain of manually mapping each property from the database to our C# class. But Dapper does that all for us. It takes the results from the statement, and checks to see if there is a property with the same name as a column, if there is, great map it! If not, don’t worry, just throw it away for now.

Query Statement Into A DTO

So the above example maps an entire database table to a C# class, but the annoying part of that is maybe we don’t need everything. Infact a very common SQL performance issue is overselecting. In our above example we actually only use the Id and EventName fields, so let’s first create a DTO with only those fields.

Then we can modify our query a bit to only select the columns we need, and make Dapper map it to our DTO :

Too easy!

Using Parameterized Queries

We haven’t really been taking user input at this point. But let’s pretend instead of always getting the Event with the ID of 1, we allowed the user to specify the Id. How can we pass that to our Dapper query while still following best practice (aka parameterizing the query).

Well again, Dapper takes care of this for us :

Pretend that eventId actually came from a GET param or any other user input. All we do is substitute an @VariableName in our SQL statement, then we add a new parameter of an anonymous object where the “Key” is the same as the @VariableName and the value is what you want it to be.

But why couldn’t I just change the line to the following?

Both look like they do substitutions, but the first actually uses proper parameters when executing the SQL statement. If you use a SQL Profiler, you will see the following for the first query :

Notice how the parameter is specified after the query, and yet for the second example where we just use string substitution :

Uh Oh, no parameters here. This opens us up for SQL Injection a plenty. But again, Dapper handles this for us with proper parameterization!

Query Multiple Rows

Up until now, we’ve been querying just a single row at a time. If we want more than one, that’s just as easy :

We just change our “QueryFirst” to a “Query” and away we go! We are instead returned a list of mapped objects which we can cycle through. Pretty easy stuff!

What’s Next

With the basics of querying using Dapper out of the way, obviously reading and writing is up next! You can check that out here!

This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work your way through!

Part 1 – The What/Why/Who
Part 2 – Dapper Query Basics
Part 3 – Updates/Inserts/Deletes
Part 4 – Dapper Contrib


For some time now I’ve been a huge fan of using Dapper in both personal and commercial projects. With more and more projects lending themselves to Microservices architecture, or at the very least a large application being made up of many smaller components, Dapper just makes sense.

But I’m getting a little tired of telling the same story of what Dapper is and what it’s capable of doing, so here’s my attempt at a “crash course” in Dapper with .NET Core.

What Is Dapper?

Dapper is classed as a “micro” ORM. That is, it’s an ORM but is extremely lightweight and gives only very basic functionality. Whereas we might class something like Entity Framework or NHibernate as a fully featured heavyweight ORM, Dapper provides minimal overhead and really only helps you out with some core basics.

Put simply, it runs your database queries from your .NET Core code, and returns results in an easy to manage fashion.

Why Dapper?

The core reason people tend to pick Dapper over something like Entity Framework is the control it affords. Under Dapper, gone are the days of using a long complex LINQ queries that generate ghastly SQL that would make any DBA shriek at first sight. Infact, with Dapper you know exactly what SQL is going to be executed…. because you wrote it. As an example, if I have a “Event” table where I want to get the “EventName” of the record with an “Id” of 1. That would look like :

No ambiguity here, I know exactly what’s going to get run.

But that probably leads us to the question of “When should I NOT use Dapper“. And it’s actually a pretty good question. Realistically I think there are two types of developers/projects that mean that Dapper may not be on the cards.

The first is if you are thinking of moving an existing project to Dapper, and that project already makes heavy use of things like EntityTracking in Entity Framework – or really any Entity Framework specific feature, then Dapper may be a stretch. There is no entity tracking to speak of in Dapper – atleast out of the box (It’s all just POCO’s), so if you are expecting some of that EF magic, Dapper isn’t for you.

The second is actually developer specific and I debate if I should even put this in here. When trying to teach junior developers Dapper, they get annoyed that they have to write raw SQL. Personally I think if you are interacting with a database at all you should know SQL to a pretty high degree. But some developers really are just happy using the LINQ they already know and love, and for some the learning curve of ASP.NET Core is large enough without adding in databases to the mix. If that’s you, and you are just getting started with C# and don’t want to learn SQL just yet, then yeah, maybe this isn’t for you.

Who Is Behind Dapper?

The brains behind Dapper are the guys over at StackOverflow. It was created because the burden on the web servers of simply taking the LINQ2SQL statements and generating SQL was often making their web boxes hit 100% CPU. Coupled with the fact that you couldn’t actually control what SQL was output from your LINQ, Dapper was born.

Best of all, Dapper is completely open source. That means you can go check out how things work, and even fix bugs if you feel that way inclined!

Next Time

So with our history lesson out of the way, let’s actually get stuck in and write some simply Dapper statements. Click here to get cracking on Querying With Dapper.

If you’ve started a new ASP.NET Core project recently, chances are you would have seen the following lines :

And chances are, you’ve also followed a tutorial that was written about a year ago that doesn’t include this line and instead has this big long winded builder instead :

Or maybe you could be coming here because you’ve been told to add the following configuration lines somewhere in your code :

But yours just “works” without it. Somehow. Magically.

I know that people comment on old tutorials from 2+ years ago that their boilerplate code no long matches what they get when creating a new project in Visual Studio. I’ve thought about going back and editing all tutorials, but instead I felt it was important to understand the simplicity of what’s going on here and that it’s really not such a big deal.

Let’s demystify.

Opening Up The Code

Before we go much further I have to say that until a few years back, I probably wasn’t as big on the open source train as I could be. But with ASP.NET being open source, I lost count of how many times I just skipped the documentation and went to the actual source code to work out what was going on or how I should approach something. This is one of those times!

We can actually head to the source code for CreateDefaultBuilder and take a look!

I’ve removed a lot of code for brevity. But as we can see, the CreateDefaultBuilder actually adds in both appsettings.json and the appsettings for our current environment. Hence why we don’t see configuration code being required elsewhere!

If we look deeper into the code we can actually see it doing a lot more of the work that we previously had to build ourselves.

What Else Is Done For Us?

When we use the CreateDefaultBuilder method, out of the box we get :

  • Sets the “Content Root” to be the current directory
  • Allows Command Line args to be pushed into your configuration object
  • Adds both appsettings.json and appsettings.{Environment}.json to be loaded into the configuration object
  • Adds environment variables to the configuration object
  • If in Development, allows the loading of secrets.
  • Adds Console/Debug loggers
  • Tells the app to use Kestrel and to load Kestrel configuration from the loaded config
  • Adds Routing
  • Adds IIS Integration

That sounds like a lot, but if we again go back to what we used to write :

It’s just now doing all of this under the hood for us (and more!). Nice!

So… This post spun a little out of control. What turned into a hunt for a simple use case (Turn an HTML string into a PDF) turned into a full blown thesis. So here’s some quick links to jump to various parts of the article if you are coming here straight from Google, it may make things a bit easier. But I do highly recommend reading from the start to get an idea of what PDF Generation really looks like on .NET Core.


Introduction

It’s a pretty common use case to want to generate PDF’s in C# code, either to serve directly to a user or to save locally. When I came to do it recently, suddenly I was over(and under)whelmed with the options available to actually achieve this. Certainly natively, there is nothing in C# or .NET Core that can generate PDF’s for you. And when it came to actually looking at feature sets of third party libraries (e.g. I want to use HTML as a template option), there were all sorts of problems.

So with that being said, instead of giving you code to generate a PDF with a particular PDF library, I’ll talk about how I evaluated each option.


What I Was Looking For

Before I set out on my journey, I wrote down 3 really crucial points that I would judge the libraries on. These aren’t too complex or even that much of an ask (Or so I hoped).

Price

Obviously free is ideal. Something open source that I can debug myself is even better. But if I do have to pay for a “premium” library. I’m looking for a one time fee that isn’t some stupid “per user/seat/machine/server” model. If I’m looking at this library as a company, I don’t want future architecture or decisions to be made based on the pricing of a library.

If there is some sort of freemium model in play, then I also wanted to make sure that the limitations weren’t too crazy (e.g. single pages only, set number of images allowed per PDF). Freemium is OK as long as the free version is actually useable.

HTML Templating (Or something close)

I had already decided that I wanted to use HTML as my templating mechanism. I was open to using some other reasonable alternative (e.g. HTML with some XSLT engine), but ideally I just want to feed an HTML file to the library and out comes my PDF. What I really don’t want to do is have to place each element manually on the PDF like we had to back in the day when printing a document from a WinForms application.

Ease Of Use/All In One

This is probably a pretty subjective one, but when you start seeking out libraries from the corners of the web or that stackoverflow answer from 3 years ago, you often end up getting some really half baked library that just doesn’t work. Whether it’s some C++ library converted to C#, a library that needs X number of other libraries to actually function, or things just plain don’t work how they should, I’m probably going to see it all. So above else, I just want to be up and running in minutes, not hours.


PDF Sharp

First up is PDF Sharp, I feel like I’ve used this one previously but I’m not entirely sure. The whole ____Sharp thing was all the rage in the early days of C#. Anyway straight off the bat PDFSharp does not work with .NET Core. There may be ported versions floating around but the version on Nuget does not support .NET Core. So it’s pretty much dead in the water. But this one was suggested to me over and over so I still want to do a quick write up about it.

Price

PDF Sharp is free and open source. They do offer paid support but don’t give any specifics on how this works and how much it costs. Free is free though so you can’t complain too much.

HTML Templating

Oh boy. HTML Templating doesn’t make it into the PDF Sharp library unfortunately. Instead we are stuck with writing syntax like we are back in the GDI+ dark days of C# :

I get it that this was what you had to do in the year 2000, but it’s just not going to fly right now. There are ways around this using another library that extends PDFSharp… But that’s still another library that you have to grab and work with. So basically, in terms of a decent template engine out of the box, it’s a fail.

Ease Of Use

Well. It doesn’t work with .NET Core which is probably going to be a blocker. The last published version was 2013. And it doesn’t have HTML rendering packaged (And the library that currently does extend it to do HTML templating also doesn’t support .NET Core). So all in all. Forget about it.


SelectPDF

I got pushed to SelectPDF by a tonne of stackoverflow answers (Kinda felt like maybe they were astroturfing a little…). It’s a paid library (Which made it all the more annoying they were commenting on stackoverflow answers with “Sure just use this great library called SelectPDF” and not mentioning the cost), But regardless I wanted to check them out and see what they offered.

Price

It ain’t free, that’s for sure. Licensing starts at $499 and goes up to $1599. Interestingly they do offer an online version where they can generate the PDF for you by sending a URL or HTML code. Honestly I think that’s way more interesting as a business model, but the pricing again starts at $19 but goes all the way up to $449 a month so I can’t really see many people taking this option.

EDIT : So weirdly enough, there seems to be a “hidden” free community edition that you can only find via a tiny footer link. You can read more about the Community Edition here. It seems like the only limitation is that you can’t generate PDFs over 5 pages. Doesn’t seem to be any limitation on commercial use. But again, seems strange to only make this a tiny footer link and not sure it anywhere else…

HTML Templating

HTML Templating is definitely here. And it seems to work well. In just a few lines we are up and running. While documentation is pretty good, I found it sort of all over the place. Loading HTML from a string versus loading HTML from a URL was all mixed together and so when reading examples, you had to check the code example to see what it was actually used for. But that being said, HTML Templating works so tick!

Ease Of Use

Here’s the code to render HTML :

So on that level, ease of use seems good. I would say that many code examples were done using old school .NET WebForms which made me uneasy. Not sure why but using such an old technology like that doesn’t make me feel like I’m using the best in class.

It’s hard to fault SelectPDF on the actual bones of what it’s doing. It generates PDF’s and does what it says on the tin. But I can’t help but feel like it’s a “budget” option for the price – It’s probably the logo not being transparent.


IronPDF

Last up, IronPDF. These guys create a bunch of libraries called IRON______ so you may have run into them before. I’ve run into them a few times for their OCR library, and that’s unfortunate because as soon as they came up, I knew the pricing was gonna be out of this world.

Price

For starters they have all these tiers. Like you can get a single project license, but you have to pay per developer (ugh). But.. If you are a SAAS company, then you have to pay per user of your SAAS product. If you are developing desktop software or something distributed, well that’s a new license again. But let’s just stick with being a SAAS company for now, for 1000+ users I’m going to be paying $1599USD for the library and a years worth of support.

In fairness, most large companies aren’t going to bat an eye at that. It’s not super crazy, and it is one off, but it’s still pretty pricey.

HTML Templating

Yes and yes. In IronPDF it just works. What impressed me the most about IronPDF was their documentation. It wasn’t just “Here’s a snippet, good luck!”. They even went as far to show you examples of how you might use Handlebars as a templating engine, implementing page breaks in your HTML, and even watermarking. To say that it’s feature rich would be an understatement.

Ease Of Use

Again, IronPDF comes up trumps when it comes to ease of use. In literally 4 lines everything just works and the output PDF is exactly as it should be :

Now here I’m using inline HTML, but I can load an HTML file or load a remote URL even and it still just works. Compared to the other libraries we’ve tried, this one is certainly the best when it comes to ease of use.


The Rest

Here are the other libraries I looked at but didn’t even bother going past the first hurdle (I sort of learnt my lesson after PDFSharp didn’t even work on .NET Core).

WKHTMLTOPDF

This shouldn’t really even be considered on the face of it. WKHTMLTOPDF is actually a binary that can generate PDF’s from HTML files, but there are a bunch of .NET wrappers to make use of it. Just felt odd to me and didn’t feel like a solution as much as it was a bunch of pieces hobbled together that should get you there in the end. Even if you do want to go through that pain, features are rather limited. But it’s free!

Spire PDF

Ridiculous pricing. Starts at $599 for a single developer and goes up to $9000 for over 10 developers. Might be OK for people who hate money but I skipped this one.

EO PDF

Another one for haters of money. Pricing starts at $749 and goes up to $4000. Support for .NET Core also seemed extremely sketchy. With the documentation half saying they support .NET Core, but to target Full Framework.

Aspose PDF

You guessed it, another one with ridiculous pricing. Starts at $999 and goes up to $14000 (Fourteen thousand) for an OEM license that still only allows 10 developers. Of course if you want the enterprise support edition you’re going up to $22000 (Twenty two thousand). Pass.

ITextSharp/IText 7

Hidden pricing which typically means “enterprise” priced where some salesman will call you to sell you on the library. Seems to work on AGPL license for free applications but rather not get into that.


Summary

So after all of that. Where does it leave us? Honestly in my opinion the only valid option right now to generate PDF’s on .NET Core is IronPDF. I know it costs but relatively speaking, $1500 is actually nothing compared to some of these other libraries. And again in my opinion, it seemed to have the most fully featured API along with the most up to date documentation. If you have another PDF option in .NET Core, feel free to drop a comment below!

EDIT : It’s been pointed out that SelectPDF does have a free community so that’s worth a crack too if you really want something out and out free. But it’s definitely still a two horse race.

 

Getting Setup With C# 8

If you aren’t sure if you are using C# 8, or you know you aren’t and want to know how to access these features. Read this quick guide on getting setup with .NET Core and C# 8. On top of that, you will need atleast .NET Core 3.0 Preview 2 – The preview is important! And then also, atleast for me, I had issues with Visual Studio going crazy and not accepting Switch Expressions but VS Code was OK. Again, this is almost like early access so if you don’t want to deal with the pain now, wait until .NET Core 3.0 and C# 8 is officially released!

Existing Switch Statements

So just in case we aren’t sure what existing Switch statements look like, let’s grab some super basic dummy code. Let’s say I have a Bank class that has a status. And based on this status I want to work out if I can walk into the bank or not.

So I might have a super simple method like so that returns if I can or can’t walk in :

Now I know this is a super obtuse example but I want to point out a couple of things.

I know that in my example, I’m returning the result anyway, but let’s pretend I want to use the value. Mind you, even if I wanted to I can’t do something like result = switch(bank.Status) to set the result. You’ll also notice just how much cruft there is in this example. Each line needs an almost redundant case and break statement even though it’s just doing one thing each.

Switch Expressions

Again I have to stress that this is only for C# 8 and above! But let’s rewrite this as a switch statement :

What the… So straight away look how succinct this is. We can assign the result of our switch statement directly to our variable, and we do away with all of that case/break junk. Pretty nice. Heck we can even rewrite it a bit to return immediately :

Hell if we really wanted to, we could get rid of some curlys as well :

I’ve been kinda critical with some C# features lately. Namely Default Interface Implementations, but.. This just makes sense!

Extending This Further

Finally, I want to just riff a little bit and show you even more of what the switch expression can do and/or look like. Some of these are actually existing features in C# to do with pattern matching, but I thought I would throw them in here because while you’re here, you may as well get them all out of the way incase you haven’t seen them yet. Now some of my examples again will seem a bit overkill, but coming up with specific examples to show all of these is actually pretty hard!

You can use a when  statement to further your switch statement. For example :

But you can also now do something called Tuple Patterns which means passing more than one parameters to the switch statement.

Note that you can use the under score (_) character to signify that it should match anything. In this case because it doesn’t matter whether they are a VIP, if the bank is closed it’s closed, then whatever that value is just match it.

And finally, you actually can now pass objects to a switch statement and inspect their properties!

This is so that instead of creating a Tuple from your properties, you just pass in the single object and you can have multiple matching statements separated by a comma. It’s really awesome stuff!

I can still remember many years ago going to a job interview that explicitly stated “We will ask you about patterns” and asking a co-worker what he thought I should read up on. To this day remember him rattling off patterns until he mentioned “singleton”, at which point I retorted “Is that even a pattern? I mean… It just kinda… is a thing… I guess?”. And by that I kind of meant that you probably use singletons every single day but you don’t really know it. Can it really be classified as a pattern?

Well, if we consult what is basically the bible in design patterns “Design Patterns: Elements of Reusable Object-Oriented Software “, we find that indeed, Singleton is in there. And so forever it stood in my bank of “interview answers” that I could have at the ready.

So What Is A Singleton?

Before we jump into specifics of .NET Core, let’s delve a bit deeper into what a singleton actually is. Trusty Wikipedia describes it as :

The singleton pattern is a software design pattern that restricts the instantiation of a class to one “single” instance.

Or, as  I describe it to other developers :

When I run this app, while it’s alive, there should only ever be one instance of this object floating around. If two classes ever ask for this object, from startup to shutdown, it should always return the same instance.

It’s actually a pretty easy thing to understand. There is never really any questions about whether you are using “singletons” or not. If you use the “Mediator pattern” for example, people may say “Oh this is just XYZ pattern with(out) ABC”. But a singleton is simply “Is there one instance for the duration of the application? OK then it’s a singleton”.

Singletons In C#

Let’s push .NET Core specifically to one side and actually look at how we might achieve a singleton pattern in just C#. Again, Wikipedia kind of gives us some hints on how we might achieve this. It states :

  • Declaring all constructors of the class to be private; and
  • Providing a static method that returns a reference to the instance.

Seems easy enough, let’s have a go at that.

Here we have a class that has a private constructor. That means the only way it can be created is within itself, which we do with a static variable. The static variable by nature is the same for the lifetime of the app.

We also have a GetInstance() method that returns the value of the static variable. This is just exposing it to the outside world.

Finally, we have a “creationCount” which counts how many times the constructor is run. We want to use this to always be sure that the constructor is only ever run once (Of course we will also compare objects later).

Let’s quickly whip up something in a console app too :

Running this we get…

Great! So we know that our constructor only ever ran once and when we compared the objects, it turned out they were the same! Awesome!

A Static Class Is Singleton Right?

The interesting thing about the above is that depending on what we actually need to do, the class itself may be static and we can simply refer to that rather than an instance instead. For example :

With this, there is only ever going to be one instance of this class floating around (The static version). This is handy especially if you need to share “state” between classes without having to do the above with a creation of an instance that is basically static anyway.

Of course there are tradeoffs with this method and realistically, I only ever use it when it’s simple shared properties. But still in my opinion, it counts as a singleton.

Singleton Scope In .NET Core

Because .NET Core comes with it’s own packaged Dependency Injection, we can of course use dependency injection to handle our singleton for us. We do this by binding our class in a singleton scope in our ConfigureServices method like so :

Now, each time a instance of IMySingletonClass is asked for, it will return the same instance every time for the lifetime of your application. I mean… Pretty simple and not much to it right!

It’s also worth nothing that in earlier versions of .NET Core there was a method called “AddInstance”, this was essentially the same as AddSingleton, therefore in later versions it was simplified to just be AddSingleton with a pass in of the object. For example :

When your application is fully “DI’d” then all of this makes sense and it’s hard to make a mistake. But if you still instantiate classes manually in your code, then you will need to be careful about people accidentally newing up this class elsewhere. Since you don’t have the whole “private constructor” thing going on, there isn’t that safety barrier to stop someone breaking your singleton pattern.

Dangers Of Singletons

Finally, I thought I would quickly touch on a couple of the biggest dangers of Singletons.

The first thing you need to ask yourself is, “Is it clear that your singleton class is a singleton to everyone else reading your code?”. One  of the biggest mistakes that I see developers make is that they think that singleton should be the default state when infact it should be the opposite. A singleton should be a special usecase when the code explicitly calls for it. It’s like making static methods. Sure there are times when making things static “could” work, but you are just giving yourself more work down the road when it suddenly doesn’t seem so viable.

And lastly, remember that the state of your singleton is shared application wide for the entire lifetime of it. Not only that, your dependencies that you only instantiate once may have state that is also suddenly shared across your entire application. I can’t tell you the number of times someone has made a “service” a singleton only to find that suddenly across web requests it’s sharing data that shouldn’t be shared. I even talk about it here under “The Singleton Transient Trap“.

The TL;DR; is. Unless you have a good reason to make something a singleton. Don’t.

This is Part 3 of a series on using the Mediator Pattern in .NET Core. You’ve probably missed out on some important stuff if you’re starting here so make sure to head back and read Part 1 before reading on!


The Mediator Pattern In .NET Core

Part 1 – What’s A Mediator?
Part 2 – Roll Your Own
Part 3 – MediatR


MediatR Library

The MediatR library describes itself as “Simple, unambitious mediator implementation in .NET”. In particular, I like the word “Unambitious” being used. It’s somewhat refreshing in a world of Hacker News posts that claim to be releasing a library that will change the way we write code forever. You may also recognize the author of MediatR as Jimmy Bogard who also maintains AutoMapper!

MediatR is essentially a library that allows in process messaging – which in turn allows you to follow the Mediator Pattern! Easy! Let’s get started

Installing MediatR

The first thing we need to do is install the MediatR nuget package. So from your package manager console run :

We also need to install a package that allows us to use the inbuilt IOC container in .NET Core to our advantage (We’ll see more of that shortly). So also install the following package :

Finally we open up our startup.cs file. In our ConfigureServices method, we need to add in a call to register all of MediatR’s dependencies.

Creating Our Handlers

The first thing to note is that MediatR can be either do “send and receive” type messages, or it can do a “broadcast” type message. Taking our example from our previous article in the series, we are doing a more broadcast style of message (And a pretty simple one at that). Let’s just stick with that for now.

In our original example, we weren’t passing through any information to our handlers, but in reality we are likely passing through some data. Basically a message if we think about traditional messaging systems. Let’s go ahead and just create a blank object that inherits from INotification  (An inbuilt type of MediatR).

Next we need handlers for the messages. That’s easy too, we just inherit from INotificationHandler  and go from there!

Super simple! We also don’t need to register these handlers anywhere, the initial line we added to our ConfigureServices method means that MediatR finds all handlers within the assembly and registers them correctly.

Creating Our Mediator Service

Now here’s the thing. We *can* just inject in the inbuilt IMediator interface everywhere and publish messages directly. Personally I’m not a huge fan because it’s basically telling everywhere “by the way, we use MediatR”. I prefer to abstract things away a little bit.

If we take our Mediator Service from the previous article, let’s just modify it a bit. Instead let’s build it like so :

So we have a NotifierService that still uses the IMediator class under the hood, but it means if we ever swap out libraries or change how we do notifications, only this class changes.

Because we have created a new service, we do need to remember to add the following line to our ConfigureServices method in our startup.cs file :

Using Our Notifier Mediator Service

Let’s use a super simple controller to run things. Again this is basically taken from Part 2 in this series and just modified a tiny bit to work with passing through notify text.

Running all of this and opening up our debug panel we can see :

Woo! Literally a 5 minute job to set up a completely in memory messaging system!

Final Thoughts On The Mediator Pattern

As we made our way through these 3 posts, it’s probably morphed a bit from the “Mediator Pattern” to “In Process Messaging”. But going back to our key bullet points from Part 1 :

  • It’s an object that encapsulates how objects interact. So it can obviously handle passing on “messages” between objects.
  • It promotes loose coupling by not having objects refer to each other, but instead to the mediator. So they pass the messages to the mediator, who will pass it on to the right person.

We can see that In Process Messaging is actually just an “implementation” of the mediator pattern. As long as we are promoting loose coupling through a “mediator” class that can pass data back and forth so that the caller doesn’t need to know how things are being handled (By whom and by how many handlers), then we can say we are implementing the Mediator Pattern.

This is Part 2 of a series on using the Mediator Pattern in .NET Core. You’ve probably missed out on some important stuff if you’re starting here so make sure to head back and read Part 1 before reading on!


The Mediator Pattern In .NET Core

Part 1 – What’s A Mediator?
Part 2 – Roll Your Own
Part 3 – MediatR


The “IEnumerable” Pattern

The “IEnumerable” Pattern is something I’ve used for the past 5 or so years in almost every single project I’ve worked on. It came about as a “that’s a cool feature” type thing when I found out that several IOC Containers would automatically inject an IEnumerable<T> into a class if you bind multiple types to the same interface (That may sound confusing but it will make sense once we get into the code).

This little hunk of code that I use isn’t specifically a “Mediator” pattern. But when I think about a core defining characteristic of the Mediator pattern :

“It promotes loose coupling by keeping objects from referring to each other explicitly”

Then this gets very close to doing so.

Let’s look at an example. For this I am going to use a standard .NET Core Web API project. Nothing fancy. In it, I have an interface with two implementations of that interface.

In my startup.cs, I then bind these two classes to the INotifier interface.

Then I have a super simple controller just to demonstrate what we’ve done.

I hit this endpoint and in my debug window, what do I see?

Super simple right? Now as I add, remove, modify the notifiers, or they add extra logic on when they need to be run. The list itself is simply injected into the controller each time (And could be injected anywhere else). In this way, the caller doesn’t actually need to change when additional classes are added or removed, and it doesn’t need to expand out it’s action, it stays exactly the same.

Making It A Bit More “Mediator”-ish

Someone looking at this might feel that it still leaks a little bit of implementation detail. But that’s easily wrapped up if we really wanted to go all out on a mediator service class. For example, let’s create a service like this :

In our ConfigureServices method of our startup.cs, we need to register this new service with the following line :

And finally, we need to go and wire this all up for use. Let’s change our controller to look a bit more like this :

That’s pretty snazzy and fits more with the Mediator pattern, but still affords us the niceness of our Mediator not having to constantly change when we add or remove handlers!

Conditional Handlers

While not strictly related to the Mediator Pattern, you’ll also often find that Mediator Pattern libraries afford ways to conditionally run a handler. This could be based on particular conditions or just a type. An extremely common pattern that I end up with is some sort of “CanRun” method being put onto the interface. It could take inputs or it could just check some data in the background. It might look like so :

Then when we need to run it from a list, we can just use Linq to filter it :

I’ve done this in a tonne of different ways with huge success.

What’s Next?

In the next article in this series we are going to take a look at the “MediatR” library. A very popular in .NET that utilizes the Mediator Pattern. You can check out that article here!