I'm trying to create a simple Hangfire test but it's not working. Here's all the important code, and how I've configured it with the Hangire.Autofac . Not sure what I'm missing here. The exception I'm getting in the /hangfire dashbaord is below also.
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();
});
}
}
However in the dashboard I keep getting this error for the task:
Failed An exception occurred during job activation. Autofac.Core.Registration.ComponentNotRegisteredException
The 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.
Figured this out eventually.
Correct Usage:
public class Service : IService {
public void MethodToQueue() { ... }
}
public class AnyOtherClass {
public void StartTasks() {
BackgroundJob.Enqueue<IService>(x => x.MethodToQueue()); //Good
}
}
Incorrect usage (what I was doing wrong)
public class Service : IService {
public void StartTasks() {
BackgroundJob.Enqueue(() => this.MethodToQueue()); //Bad
}
public void MethodToQueue() { ... }
}
public class AnyOtherClass {
public AnyOtherClass(IService service) {
service.StartTasks();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With