In a previous post we looked at how we can publish a single exe from a .NET Core project. Now in it, I talk about how the resulting binary is absolutely massive, 70MB for a simple hello world console app! But I also talked about how there are now ways to significantly chop that down.

Despite that, when shared with Reddit, there was some comments that weren’t so impressed. Most notably this gem :

But that’s cool. For Scellow and anyone else that wasn’t impressed with the size of the exe, let’s look at how we can chop it down.

You Need .NET Core 3.0 (Preview 6+)

Like all these features I’m writing about recently, you’re gonna need the very latest version of .NET Core 3.0. At the time of writing it’s Preview 6. Any version earlier will simply not fly. And again, if that isn’t you and you don’t want to muck around with preview versions, then you’ll just have to wait!

PublishedTrimmed Flag

Before we go on, you might hear IL Linker talked about a lot. Possibly because it’s in the title of this post! But that’s because IL Linker is essentially the backbone of this entire feature. However where previous it was this external tool you had to grab from a nuget feed, now it’s built directly into .NET Core 3.0+ which is pretty impressive!

Anyway we previously published our application using the following command :

And with that, we ended up with an exe over 70MB big :

Not good. But literally all we have to do is add one flag and we can chop it down a bit :

So… 29MB. And this is about the time where you go “but shouldn’t this be KB in size?”. And honestly the answer is yes. It should be. But we have to remember that this is still a completely self contained application that doesn’t even require the target machine to know what .NET Core is. So even if we aren’t using things like say.. cryptography so we can get rid of that, there is probably a lot of basic and primitive .NET Core features that we just can’t get rid of.

Still. It’s an exe half the size with no functional difference between the two.

Reflected Assemblies

Through various forms of reflection, we may end up loading assemblies at runtime that aren’t direct references. Take this (very convoluted) example of loading an assembly at runtime :

Now when debugging this locally, and we have .NET Core installed, we ask for System.Security and it knows what that is because we are using the installed .NET Core platform. So running it, we get :

But if we publish this using the PublishTrimmed flag from the command line, then run it :

Unsurprisingly, we have trimmed a bit too much off. Because I don’t actually reference System.Security anywhere, it’s decided we aren’t actually using it. But there is a way to specify that we know best, and to package it up for us.

All we need to do is edit our csproj file for our project and add :

Now we will bundle up System.Security with our single exe and everything will run smooth! Pretty nice I have to say!

You may ask yourself “Well how will I know when I need to do this?”. Frankly 99% of the time you won’t. If you decide to trim your exe, you will need to really give it a good test before letting it out into the wild.

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!

Say I have a simple “Hello World” console application that I want to send to a friend to run. The friend doesn’t have .NET Core installed so I know I need to build a self contained application for him. Easy, I just run the following command in my project directory :

Pretty self explanatory :

  • Publish the project from the current directory
  • Build the project to run on Windows 64 bit machines
  • Build in release configuration mode
  • Publish everything as “self-contained” so that everything required to run the app is packaged up with our executable

So this works right, we end up with a folder that has our exe and everything that is required to run it, but the issue is that there is a tonne required to run even a HelloWorld console app.

All up it’s a little over 200 files. Crazy – but it makes sense. It’s essentially having to package the .NET Core runtime just to run Hello World.

So functionally, this works. But optics wise, it looks like a mess. I’ve sent folders like this to clients and had to say “uhh.. So I’m going to send you a folder with hundreds of files in it… But… Can you just find the one titled MyApplication.exe and run that and don’t worry about the rest?”. When people are used to having an icon on their desktop they double click and things just.. work… This just doesn’t cut it.

You Need .NET Core 3.0 (Preview 5+)

I need to put that in bold because this will not work if you don’t have .NET Core 3.0. And if you are an early adopter (At the time of this post .NET Core 3.0 is not GA yet), you will need atleast preview 5 upwards. If you’re not one to mess around in preview’s, then you can just wait a few months till .NET Core 3.0 is released!

The PublishSingleFile Flag

All that intro and it literally comes down to a single command flag :

All this does is runs our publish command but tells it to package it within a single file. You’ll notice that we no longer specify the self-contained flag. That’s because it’s assumed that if you are packaging as a single exe, that you will want all it’s dependencies along with it. Makes sense.

And the output :

A single tidy exe! When this is executed, the dependencies are extracted to a temporary directory and then everything is ran from there. It’s essentially a zip of our previous publish folder! I’ve had a few plays around with it and honestly, it just works. There is nothing more to say about it. It just works.

Helpful Tip : Make sure you clean your publish directory or just outright delete your bin folder. It doesn’t break anything to not do so, but all those old DLL’s just hang around until you do so your nice single EXE is hard to spot. 

File Size And Startup Cost

Keen eyes will notice something about the above screenshot. The file size. It’s over 70MB! That’s crazy for an application that does nothing but print Hello World to the screen! This is solved in Preview 6 of .NET Core 3.0 with a feature called IL Linker or Publish trimmer that omits DLL’s that aren’t used. You can read more about that here!

The other issue you may find is that there is a slight startup cost when running the self contained executable for the first time. Because it needs to essentially unzip all dependencies to a temporary directory on first run, that’s going to take a little bit of time to complete. It’s not crazy (5 seconds or so), but it’s noticeable. Luckily on subsequent runs it uses this already unzipped temp folder and so startup is immediate.

Dec 14, 2016.

That’s the date I registered dotnetcoretutorials.com. A week later I would register dotnetcoretutorial.com because I was worried someone would just chop off the “s” from the end and copy me.

Almost 3 years later and I have seen some crazy things with this platform. The “poopooing” of the project.json format, the deprecation then un-deprecation of ASP.NET Core running on full framework, and now the introduction of desktop apps to run on .NET Core.

Through all of that, I get a steady stream of emails asking for help on projects. It goes from individuals asking me to take a squiz at their github projects and point out glaring mistakes, all the way to large corporates getting me to build a migration plan on how they can get their existing .NET Framework project onto .NET Core. So that’s why I’m…

“Opening up the consultancy”

That’s probably a bit of an over the top statement. But it’s more like I’ve updated a couple of pages on the website to make it clear that there is no harm in reaching out and seeing how we can work together. I try and reply to each and every email even if I can’t be of too much help at the time.

So go ahead, contact me and get your .NET Core project moving today!

A Word On Product Posts

While not strictly related to consulting. I did want to mention “product posts” that sometimes pop up here from time to time. These might be posts on hosting platforms, dev tooling, monitoring solutions, or any other “paid” product used in software development.

I at times get emails from companies looking to promote their new tool, and they want me to do a nice write up on how amazing it is. But…

  • If I personally would not use the product, I do not write about it.
  • If I think the product is overpriced, I do not write about it.
  • If I feel that there is a snake oil element to the product (misleading landing pages, promises etc), I do not write about it.

Very few products make it past this line, and therefore ones that I do write about are ones that I actually use myself. This does mean that the majority of requests I get to write posts do not actually make it onto the blog, but I think it’s important that readers trust that when I write about the product, it’s worth their money.

So with all that being said, I just want to make it clear that yes, sometimes companies contact me asking to write about their product. But if I do write about it, it’s my own words with my own personal experience with the tool.

With that out of the way, if you have a product used in software development you think would benefit readers, you can contact me here.

.NET Core 3.0 Preview 6 has been released as of June 12th. You can grab it here : https://dotnet.microsoft.com/download/dotnet-core/3.0

What’s Included

The official blog post from Microsoft is here : https://devblogs.microsoft.com/dotnet/announcing-net-core-3-0-preview-6/ . But of course if you want the cliff notes then…

Docker Images For ARM64

Previously docker images for .NET Core were only available for X64 systems, however you can now grab ’em for ARM64 too!

Ready To Run Images

Probably the most interesting thing contained in this release is the “Ready To Run” compilation ability. If you’ve ever used NGEN in previous versions of the .NET Framework, or attempted to some ahead of time jitting to improve your applications startup performance, then this is for you.

Better Assembly Linking

It’s always been possible to publish self contained applications in .NET Core that don’t require the runtime to be present on the destination machine. Unfortunately this sometimes made self contained apps (even one’s that did nothing but print Hello World!) become massive. Preview 6 contains a way to trim the required assemblies to reduce the footprint by almost half.

HTTP/2 Support In HTTPClient

HTTP/2 support has reached .NET Core! The default is still HTTP/1.1, but you are now able to opt in to create connections using a specific version. HTTP/2 opens up the world of multiplexed streams, header compression and better pipelining.

Worth Updating?

Probably the biggest thing for most developers in this version is HTTP/2 support. It’s likely something that will become defacto in the future so if you want to get ahead of the curve, get stuck in!

Ready To Run images are also pretty huge. If you remember that famous blog post from the Bing team around performance improvements they gained from switching to .NET Core 2.1 (https://devblogs.microsoft.com/dotnet/bing-com-runs-on-net-core-2-1/), a big factor was ahead of time compiling of the code. So it’s definitely going to change the game for a lot of companies running .NET Core code.

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!

This is part 1 of a series on using the Mediator Pattern in .NET Core. It’s a pretty good place to get started!


The Mediator Pattern In .NET Core

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


A couple of years back, I had to help out on a project that was built entirely using the “Mediator Pattern”. Or more specifically, built entirely using the MediatR library. There were all these presentations about the “theory” behind the Mediator Pattern and how it was a real new way of thinking. I couldn’t help but think… We’ve been doing this for years. Except we just call it good programming… Infact I had my own pattern which we’ll look into in Part 2 that I called the “IEnumerable Pattern” which achieved the same thing.

But it’s taken all these years to finally write it all down. So here it is. Here’s the Mediator Pattern in C# (Or more specifically, .NET Core).

The Mediator Pattern “Definition”

The Mediator Pattern actually dates all the way back to 1994 in the famous book “Design Patterns: Elements of Reusable Object-Oriented Software”. But I feel like it’s only really sprung up again lately due to a slew of libraries trying to implement the pattern.

In a nutshell, the definition (as stolen from Wikipedia) is :

The essence of the Mediator Pattern is to “define an object that encapsulates how a set of objects interact”. It promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to be varied independently. Client classes can use the mediator to send messages to other clients, and can receive messages from other clients via an event on the mediator class.

So let’s break it down a little into two bullet points that we will refer back to later.

  • 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.

That’s honestly it.

And when you think about just those two bullet points in isolation. It sounds awfully like a message hub of sorts right? That’s because… It actually kinda is. It’s like a message hub in code. When you send a message through a typical message hub, you don’t know who is receiving that message, you just know that the hub knows and it will sort it out for you.

In Visual Form

If we break this out into visual form using my (very limited) lucidchart skills. It looks a bit like this :

This is probably a simplified version of it because a Mediator Pattern does allow two way communication, it’s not just a one way broadcast, but I think this is the model we are going to try and use going forward in our examples.

Again, looking at it this way, it’s hard not to see the comparisons to messaging systems. But on the other hand, it’s hard not to also feel like this could very quickly turn into one of those “super” classes where sure, MyService doesn’t reference every handler… But the Mediator does. But there are ways to handle that which we will go into later.

Why?

And finally, the “Why?”. Why is this even a thing?

Well if we take the diagram above, if we had MyService calling other handlers directly (For example notifying them about an action), then as we add handlers, MyService has to start referencing them all even if it doesn’t care about the result. For example, our service might start looking like this :

So what happens when we add more handlers? Or remove handlers? Our service keeps changing when in reality it doesn’t really care who gets notified.

Using a Mediator Pattern, it may instead end up looking like :

So there’s the bonus that as handlers change, get added or removed, the service itself doesn’t change. But there is also a bit of a downer that we are maybe shifting the load to the Mediator, it’s job is now to manage the handlers and how they get notified. But this makes sense right! To have a class whose sole job is to notify clients should be able to change depending on how those clients need to be notified. And our service which really doesn’t care about the implementation details of those handlers can get on with it’s work.

In saying that, later on we will see how we use DI to really help us ease the load from both classes and yet still stick to heart of the Mediator Pattern.

What’s Next?

In the next article in this series, we are going to look at a pattern that I dubbed the “IEnumerable” pattern. It’s essentially the Mediator Pattern with some dependency injection thrown in! You can check out that article here!

Hosted Services in the .NET Core world mean background tasks in everyday developer terms. If you’re living in the C# world, and even the Azure world, you actually already have a couple of options for doing background style tasks. Problems that you can solve using Hosted Services are probably similar to the problems you currently solve using Windows Services or Azure WebJobs. So first, let’s take a look at some comparisons.

Hosted Services vs WebJobs

WebJobs are similar to hosted services in that they run on the same machine as an Azure Website – thus sharing resources. WebJobs do have the added benefit of being able to be deployed separately (Hosted services are part of the website) and have additional functionality when it comes to running as a singleton. With Hosted Services, there is an instance running of that hosted service for every deployment of your website which can be an issue if you only want one instance of that “process” running at anytime. You can program around this by creating your own locking mechanism, but obviously webjobs gets this out of the box. The one other difference really is that with the WebJobs SDK, you get things like queue/blob triggers right away. Inside a ASP.NET Core Hosted Service, you would need to write all of this manually.

Hosted Services vs Windows Services

Windows Services are typically hosted on other infrastructure that isn’t also hosting your website. They can be deployed independently, and don’t have really any tie in to your website. But that also comes as a negative. If you are using PAAS on something like Azure or Google Cloud, you would then need a separate VM to hosted your Windows Service. Not too great!

Hello World Hosted Service

Create a new class in your .NET Core Web Project called “HelloWorldHostedService”. This is going to be your first piece of code for your Hosted Service :

So all we are doing is starting a timer that every 10 seconds, prints out “Hello World!” to the debug output.

You’ll notice that we have a start and stop, probably pretty similar to a windows service where the StartAsync method is when our web process kicks off. It shouldn’t be where we do work, but instead where we setup side threads to do the work. And stop is where our web process stops, so we obviously have to pause our timer.

You’ll also need the following line, in your ConfigureServices method, in your startup.cs.

And that’s it, that’s your first hosted service. If you run your web project, your service should kick off (Either set a breakpoint or check the Debug output), and away you go!

Background Service Helper

The thing is, each time you write a background service, it’s likely to be the same sort of process. It’s probably going to either be something on a timer, or in an infinite loop. So 9 times out of 10, you’re going to be using some sort of boiler plate that kicks off your task on a different thread, and handles cancellation tokens etc.

Well Microsoft foresaw this, and create an abstract helper class called BackgroundService. We can rewrite our above code to instead look like :

Notice that we now inherit from BackgroundService and not from IHostedService. But our startup.cs call doesn’t change.

Behind the scenes, the code for BackgroundService looks like (And you can see the full source on Github here) :

So it’s actually pretty simple. It’s just kicking off a thread with your work, and waiting for it to finish (If it finishes). It’s handling the cancellation tokens for you, and a bit of cleanup.

Good Examples Hosted Services

I thought I would end on what makes a good hosted service. It should be something preferably specific to that instance of the website. If you scale out horizontally, each instance of the hosted service shouldn’t compete with each other and cause issues. So things like clearing a shared cache, moving files/data, ETL processes etc may not be great candidates for hosted services because each service will be competing with each other.

An example of a service I wrote recently was that I built an API that read data from a secondary replica database. I didn’t mind if the replica fell behind in updates from the primary, but it still couldn’t fall too far (e.g. More than 15 minutes). If it fell more than 15 minutes, I wanted to force my API to instead read from the primary. Each website checking the secondary status and swapping to read from primary is very scalable because the check itself is atomic and no matter how many times it’s called, it doesn’t interfere with each other.