Setting Up Structure Map With Hangfire

In this tutorial, you will learn how to use dependency injection with Hangfire. Having high test coverage within your code should be your aim.

This article assumes that you have the following packages installed within your project:

  • Hangfire
  • Hangfire.StructureMap
  • StructureMap
  • StructureMap.MVC5

Let's Get Going

Setting up 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.  Long and short of it, you will need a StartUp class that registers Hangfire, like this:

    public class Startup
        public void Configuration(IAppBuilder app)
            GlobalConfiguration.Configuration.UseSqlServerStorage("My Connection String");
IContainer container = IoC.Initialize(); GlobalConfiguration.Configuration.UseStructureMapActivator(container); app.UseHangfireDashboard(); app.UseHangfireServer(); } }

To enable structure map to work with Hangfire, as long as you have the Hangfire Structure Map Nuget package installed and the MVC structure map package, in your config, you just need to register your structure map DI container with the Structure map activator. 

It's worth noting, you may get concurrency issues if you try and use the same container set-up as your website  Hangfire recommends registering the dependencies separately using something like this:

            return new Container(c =>

With that config set, you should be able to use constructor injection, rather than having to deal with static classes.  With structure map setup you can pass non-static classes into it, like so:

BackgroundJob.Enqueue(myService => myService.method());


submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top