Hangfire problem with .net core and DI

I am working on a Asp net core project with Hangfire (Pro) integration (with Redis) and most stuff works fine but I am having difficulties finding out the proper way to define to use dependency injection with recurring jobs.

More precisely I have a service A with a dependency on my database Context, BContext of type DbContext that get’s injected with Asp net core DI.
I need to call a method on that service A repeatably.
I tried different options in the Configure method of Startup class such as
recurringJobManager.AddOrUpdate("some text", Job.FromExpression(() => serviceA.DoSomething()), Cron.MinuteInterval(limsSettings.PollEveryMinutes));
with recurringJobManager resolved of type IRecurringJobManager

or
RecurringJob.AddOrUpdate(() => serviceA.DoSomething(), Cron.MinuteInterval(limsSettings.PollEveryMinutes));

and some other options

But I always get an exception of

{MySql.Data.MySqlClient.MySqlException: There is already an open DataReader associated with this Connection which must be closed first.
   at MySql.Data.MySqlClient.MySqlCommand.VerifyValid()
   at MySql.Data.MySqlClient.MySqlCommand.<ExecuteReaderAsync>d__50.MoveNext()

which I think is due to the fact that the DbContext is serialized and Hangfire is being de-serialized with a connection that has already been closed.

If you can help me, that’d be awesome :slight_smile:

Some EF providers (like SQL Server) support MARS (Multiple Active Result Sets) feature, which can be enabled in connection string by specifying MultipleActiveResultSets=True.

Unfortunately, MySQL seems to still lack this feature, and your service is likely trying to execute next query while still processing the results of a previous one, hence the exception. There’s a lot of similar issues with proper explanations on Google, but they’re all about the same: don’t perform new queries while still processing the results of a previous one. Rather use joins (which will result in a single request), or materialize query results (by calling ToList()/ToArray()/ToDictionary() before enumeration).

Thanks. I really forgot one ToList()

Also regarding DI and this issue.

Is the following the correct way to configure ASP Net Core with Hangfire

  provider = services.BuildServiceProvider();

            var scopeFactory = (IServiceScopeFactory) provider.GetService(typeof(IServiceScopeFactory));
            services.AddHangfire(x =>
            {
                x.UseRedisStorage(redisIp, redisOptions);
                x.UseActivator<AspNetCoreJobActivator>(new AspNetCoreJobActivator(scopeFactory));
            });

The problem here is that my DbContext is not correctly resolved with all it’s dependencies.