Registering IBackgroundJobClient with Unity IoC

I have a webAPI project using OWIN startup to configure hangfire. I’m also using Unity IoC.

I have a service, and in that service I call BackgroundJob.Enqueue() to start a job. All good.

Now i need to add unit testing (using Moq). So, my instinct tells me that I need to switch from calling the static BackgroundJob.Enqueue() in my service to calling an injected IBackgroundJobClient dependency via Unity.

The problem: my Unity container is constructed in the webApiConfig.Register method. If I attempt to register IBackgroundJobClient in this method, it raises an exception saying storage is not yet set. This is what I’m attempting:

container.RegisterType<IBackgroundJobClient, BackgroundJobClient>(new InjectionConstructor());

And this is simply because Hangfire storage has not yet been initialised. This happens later in the OWIN startup config methods.

My current solution is to create a global variable in my WebApiConfig class which holds a reference to my Unity container. I then use the reference to register IBackgroundJobClient after OWIN startup has completed. This works, but doesn’t feel right.

Can anyone offer a better solution?

Secondly, when registering IBackgroundJobClient with unity, should i use RegisterType or RegisterInstance i.e. should i create a new job every time? I believe Unity will clean up by calling IDispose.

Thanks for any advice.

I use injection factory to lazy-initialize the mapping:

// JobStorage.Current isn't set until hangfire finishes initializing itself, which is after we've set up unity, // so lazy-bind it instead of using RegisterInstance container.RegisterType<JobStorage>(new InjectionFactory(c => JobStorage.Current));

I’m experiencing the same problem. Is this resolved yet? Are you able to paste how you were able to resolve it?