How can I use .net core's default dependency injection in Hangfire ?
I am new to Hangfire and searching for an example which works with asp.net core.
How can I use .net core's default dependency injection in Hangfire ?
I am new to Hangfire and searching for an example which works with asp.net core.
I had to start HangFire in main function. This is how I solved it:
DoritoBandito's answer is incomplete or deprecated.
Register services:
Enqueue:
Source: http://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html
See full example on GitHub https://github.com/gonzigonz/HangfireCore-Example.
Live site at http://hangfirecore.azurewebsites.net/
Make sure you have the Core version of Hangfire:
dotnet add package Hangfire.AspNetCore
Configure your IoC by defining a
JobActivator
. Below is the config for use with the default asp.net core container service:Next register hangfire as a service in the
Startup.ConfigureServices
method:Configure hangfire in the
Startup.Configure
method. In relationship to your question, the key is to configure hangfire to use the newHangfireActivator
we just defined above. To do so you will have to provide hangfire with theIServiceProvider
and this can be achieved by just adding it to the list of parameters for theConfigure
method. At runtime, DI will providing this service for you:When you enqueue a job, use the registered type which usually is your interface. Don't use a concrete type unless you registered it that way. You must use the type registered with your IoC else Hangfire won't find it. For Example say you've registered the following services:
Then you could enqueue
DbManager
with an instantiated version of the class:However you could not do the same with
MyService
. Enqueuing with an instantiated version would fail because DI would fail as only the interface is registered. In this case you would enqueue like this:As far as I am aware, you can use .net cores dependency injection the same as you would for any other service.
You can use a service which contains the jobs to be executed, which can be executed like so
var jobId = BackgroundJob.Enqueue(x => x.SomeTask(passParamIfYouWish));
Here is an example of the Job Service class
And in your projects Startup.cs you can add a dependency as normal
services.AddTransient< IClientService, ClientService>();
Not sure this answers your question or not
Currently, Hangfire is deeply integrated with Asp.Net Core. Install Hangfire.AspNetCore to set up the dashboard and DI integration automatically. Then, you just need to define your dependencies using ASP.NET core as always.