I have a .NET core WebAPI project that uses Hangfire for background jobs. I am trying to setup Simple Injector for DIs. My porject has an IFoo
and a Foo
class that looks as follows
public interface IFoo
{
void DoSomething();
}
public class Foo : IFoo
{
public Foo() { }
public void DoSomething()
{
Console.WriteLine($"Foo::DoSomething");
}
}
Below is how I setup the Simple Injector container. I am using Hangfire.SimpleInjector
nuget package
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var container = new SimpleInjector.Container();
container.Register<IFoo, Foo>();
GlobalConfiguration.Configuration.UseActivator(
new Hangfire.SimpleInjector.SimpleInjectorJobActivator(container));
services.AddHangfire(x => x.UseSqlServerStorage(<My Connection string>));
services.AddHangfireServer();
services.AddControllers();
}
}
The background job is setup as following in controller
public IActionResult DoSomething()
{
var jobID = BackgroundJob.Enqueue<IFoo>( x => x.DoSomething());
return Ok();
}
But this job fails with following stack trace.
An exception occurred during processing of a background job.
System.InvalidOperationException A suitable constructor for type 'MyWebAPI.Controllers.IFoo' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider, Type, Object[])
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider, Type)
at Hangfire.AspNetCore.AspNetCoreJobActivatorScope.Resolve(Type type)
at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_0.<PerformJobWithFilters>b__0()
at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter, PerformingContext, Func`1)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_1.<PerformJobWithFilters>b__2()
at Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext, IEnumerable`1)
at Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext, IStorageConnection, String)
What am I doing wrong in setting all this up?
I am not sure the DI in Hangfire
is for this purpose.
You need dependency injection to resolve inner dependencies, not to resolve the main type you want to use.
You can check the documentation here.
Check this answer with same problem.