0

我正在使用 hangfire 来启动后台作业,但是当我尝试使用 hangfire autofac 与 generic 的集成来自动解决它不起作用的任务服务时遇到了问题,因为它无法解决依赖项之一。我想是因为我没有收到任何错误。

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

如果我通过自己解决来使用相反的方法,它就可以工作。

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

我发现在我的构造函数中,我有一个导致问题的测试服务。如果我在构造函数中删除服务,服务就会得到解决。

    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>();            
      }

我在启动类中配置了 autofac,如下所示:

    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);

    }
4

1 回答 1

1

我发现我的问题是我没有从配置服务函数返回服务提供者**,而是将函数创建为 void 并且什么也不返回。

    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);**
    }
于 2017-07-27T15:53:33.583 回答