Hangfire Autofac integration is not able to resolve service with registred dependency

1.1k views Asked by At

I'm using hangfire to lauch background job but I have a problem when I try to use the hangfire autofac integration with generic to resolve automaticly the task service it's not working because it's is not able to be resolve one of the dependency. I suppose because I don't receive any error.

 BackgroundJob.Enqueue<IBackgroundTask>(x => x.RunAsync() );  

If I use the other way around by resolving by myselft it's working.

 var service = ApplicationContainer.Resolve<IBackgroundTask>();    
 BackgroundJob.Enqueue(() => service.RunAsync() );

I figured out that in my constructor I have a test service that cause the problem. If I remove the service in the constructor the service get resolved.

    public class ConvertCarteCreditService : IBackgroundTask
    {
      private readonly ILogger logger;
      private readonly ITest testService;

      public BackgroundTask(ILogger logger, **ITest test**)
      {
        this.logger = logger;
        this.testService = test;
        // this.testService = Startup.Resolve<ITest>();            
      }

I have configured autofac in the startup class like this :

    public void ConfigureServices(IServiceCollection services)
    {

     var builder = new ContainerBuilder();

     ServiceLayerInstaller.ConfigureServices(builder);                   
     DataLayerInstaller.ConfigureServices(builder, connectionString,  readOnlyConnectionString);

     builder.RegisterAssemblyTypes(typeof(WorkerRoleInstaller).
GetTypeInfo().Assembly).Where(t => t.Name.EndsWith("Test"))
.AsImplementedInterfaces();

     WorkerRoleInstaller.ConfigureServices(builder);

     builder.Populate(services);
     ApplicationContainer = builder.Build();

     var autofacJobActivator = new AutofacJobActivator(ApplicationContainer);       

     GlobalConfiguration.Configuration.UseActivator(autofacJobActivator);

    }
1

There are 1 answers

0
jboo On

I found my probleme was that I didn't return the service provider** from the configures services function but instead create the function as void and return nothing.

    public **IServiceProvider** ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDirectoryBrowser();            
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        var builder = new ContainerBuilder();

        builder.Populate(services);

        ServiceLayerInstaller.ConfigureServices(builder);                    

        WorkerRoleInstaller.ConfigureServices(builder);

        ApplicationContainer = builder.Build();

        var autofacJobActivator = new AutofacJobActivator(ApplicationContainer, false);
        GlobalConfiguration.Configuration.UseActivator(autofacJobActivator);

        **return new AutofacServiceProvider(ApplicationContainer);**
    }