In this tutorial, you will learn how to use StructureMap with Hangfire. The point of this tutorial is to prevent you from having to use static classes when scheduling tasks with Hangfire. Having high-test coverage within your project should is a great aim to strive for. Hangfire is a really good scheduling solution for .NET projects, however, it can be a little tricky getting it under test when using StructureMap. This is where this guide will help you. In this tutorial, I will show you everything you need to get the two working in perfect harmony... ahh! This article assumes that you have the following packages installed within your project:
- Hangfire
- Hangfire.StructureMap
- StructureMap
- StructureMap.MVC5
Setting up a structure map is really simple. First, ensure that you have the above-mentioned packages. If you follow any good Hangfire set-up guide, like How To Integrate Hangfire Into The Umbraco Backend. The long and short of it, you will need a StartUp.cs
class that registers Hangfire. The class should look like this:
To configure the structure map to work with Hangfire, ensure the Hangfire Structure Map NuGet package is installed as well as the StructureMap.MVC5/ package. In your Structure map activator class, you will now need to add some config. Hangfire recommends registering the dependencies separately to prevent concurrency issues. This is done using this config:
After implementing this config within your StructureMap container, you should be able to use constructor injection when you start queuing tasks with HangFire. This is a much better approach compared to passing in static classes when using Hangfire 🔥🔥🔥
With this config, you will now be able to pass dependencies into the Hangfire scheduling code. This will allow you to more easily test your scheduling code as well. An example of some code to schedule a non-static class within Hnagfire can be seen below. This was taken from some production code and I confirm it worked brilliantly!
Happy Coding 🤘