Using Hangfire: generic Enqueue<T> method throws exception
Asked Answered
U

1

8

I've got a simple .NET 4.5 console app with Hangfire.Core and Hangfire.SqlServer packages installed.

In my main method I enqueue a background job like this:

BackgroundJob.Enqueue<Test>((t) => Console.WriteLine(t.Sum(3,4)));

My Test class looks like this:

public class Test
{
    public Test(){ }

    public int Sum(int a, int b)
    {
        return a + b;
    }
}

When i F5 my program I get an exception on the line with Enqueue:

"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll Additional information: variable 't' of type 'HangfireTest.Test' referenced from scope '', but it is not defined"

When I create my Test class in code with "new" and use non-generic Enqueue method - everything works:

BackgroundJob.Enqueue(() => Console.WriteLine(new Test().Sum(3,4)));

But I need a generic one, cause I'd like to create an interface ITest 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?

Unsay answered 24/6, 2016 at 7:22 Comment(1)
It seems your variable t is never instantiated.Entremets
C
6

You cannot consume the return value of the background method in the scope of the calling method. This feature is not supported out of the box. You may consider asynchronous operation if that is your requirement. There is a workaround for this as discussed here.

With Hangfire, what you can do instead is wrap the Consonle.WriteLine part in a separate job and enqueue that as background job.

So your revised class might look like something this -

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 you will be able to enqueue jobs now like this -

BackgroundJob.Enqueue<Test>(t => t.SumJob(3, 4));
Conto answered 24/6, 2016 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.