我正在尝试创建一个简单的Hangfire测试,但它不工作.以下是所有重要的代码,以及我如何使用Hangire.Autofac进行配置.不知道我在这里失踪了我在/ hangfire dashbaord进入的例外也在下面.
public class AmazonSqsService : IAmazonSqsService { private readonly IBackgroundJobClient _backgroundJobClient; private readonly ILogService _logService; public AmazonSqsService(IBackgroundJobClient backgroundJobClient,ILogService logService) { _backgroundJobClient. = backgroundJobClient; _logService= logService; } public async Task<string> Test() { return _backgroundJobClient.Enqueue(() => Looper()); } public void Looper() { while (true) { _logService.Info("In Looper Loop"); Thread.Sleep(5000); } } } public partial class Startup { public static IContainer ConfigureContainer() { var builder = new ContainerBuilder(); RegisterApplicationComponents(builder); AppGlobal.Container = builder.Build(); } public static void RegisterApplicationComponents(ContainerBuilder builder) { builder.RegisterType<LogService>().As<ILogService>().InstancePerLifetimeScope(); builder.RegisterType<AmazonSqsService>().As<IAmazonSqsService>().InstancePerLifetimeScope(); builder.RegisterType<BackgroundJobClient>().As<IBackgroundJobClient>().InstancePerLifetimeScope(); builder.Register(c => JobStorage.Current).As<JobStorage>().InstancePerLifetimeScope(); builder.Register(c => new StateMachineFactory(JobStorage.Current)).As<IStateMachineFactory>().InstancePerLifetimeScope(); } public static void ConfigureHangfire(IAppBuilder app) { app.UseHangfire(config => { config.UseAutofacActivator(AppGlobal.Container); config.UsesqlServerStorage("DefaultDatabase"); config.UseServer(); }); } }
但是在仪表板中,我不断得到这个错误的任务:
Failed An exception occurred during job activation.
Autofac.Core.Registration.ComponentNotRegisteredExceptionThe requested service ‘App.Services.AmazonSqsService’ has not been registered. To avoid this exception,either register a component to provide the service,check for service registration using IsRegistered(),or use the ResolveOptional() method to resolve an optional dependency.
解决方法
最终确定了这一点.
正确使用方法
public class Service : IService { public void MethodToQueue() { ... } } public class AnyOtherClass { public void StartTasks() { BackgroundJob.Enqueue<IService>(x => x.MethodToQueue()); //Good } }
使用不当(我做错了什么)
public class Service : IService { public void StartTasks() { BackgroundJob.Enqueue(() => this.MethodToQueue()); //Bad } public void MethodToQueue() { ... } } public class AnyOtherClass { public AnyOtherClass(IService service) { service.StartTasks(); } }