Using Hangfire: the general Enqueue <T> method throws an exception
I have a simple .NET 4.5 console application with the Hangfire.Core and Hangfire.SqlServer packages installed.
In my main method, I run a background job like this:
BackgroundJob.Enqueue<Test>((t) => Console.WriteLine(t.Sum(3,4))); The My Test class is as follows:
public class Test { public Test(){ } public int Sum(int a, int b) { return a + b; } } When I F5 my program, I get an exception in the line with Enqueue:
"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll Additional information: variable 't' of type 'HangfireTest.Test' referencing the scope '', but this is not defined."
When I create my test class in code with "new" and use the non-generic Enqueue method, everything works:
BackgroundJob.Enqueue(() => Console.WriteLine(new Test().Sum(3,4))); But I need a generic one, because I would like to create an ITest interface and use dependency injection to do something like this:
BackgroundJob.Enqueue<ITest>((t) => Console.WriteLine(t.Sum(3,4))); So what am I doing wrong here?
You cannot use the return value of a background method in the scope of the calling method. This feature is not supported out of the box. You may consider asynchronous operation if this is your requirement. There is a workaround for this, as discussed here .
Using Hangfire, you can instead wrap part of Consonle.WriteLine in a separate task and queue it as a background task.
So your revised class might look something like -
public class Test { public Test() { } public int Sum(int a, int b) { return a + b; } public void SumJob(int a, int b) { var result = Sum(a, b); Console.WriteLine(result); } } ... and now you can queue a job like this -
BackgroundJob.Enqueue<Test>(t => t.SumJob(3, 4));