Hi! I have a console application that uses a generic host and starts a Hangfire server to process some background jobs.
static async Task Main(string[] args)
{
Console.Clear();
Console.Title = "Hangfire Server";
// Configure and start NServiceBus endpoint
using (var host = ConfigureEndpoint(Host.CreateDefaultBuilder(args))
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(ConfigureContainer)
.Build())
{
await host.StartAsync();
// Hangfire server
GlobalConfiguration.Configuration.UseSqlServerStorage(@"Server=HFSERV; Database=Hangfire.PAM; Integrated Security=True");
using (var server = new BackgroundJobServer())
{
Console.WriteLine("Hangfire Server started. Press Ctrl+C to exit...");
}
await host.WaitForShutdownAsync();
}
}
static IHostBuilder ConfigureEndpoint(IHostBuilder builder)
{
builder.UseConsoleLifetime();
// configure logging
builder.ConfigureLogging((ctx, logging) =>
{
logging.AddConfiguration(ctx.Configuration.GetSection("Logging"));
logging.AddEventLog();
logging.AddConsole();
});
// configure NSB endpoint
builder.UseNServiceBus(ctx =>
{
var endpointConfiguration = new EndpointConfiguration("Hangfire.Server");
endpointConfiguration.EnableInstallers();
var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();
transport.ConnectionString("host=localhost");
transport.UseConventionalRoutingTopology(QueueType.Classic);
endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
return endpointConfiguration;
});
return builder;
}
When a background job is finished, it should send a message to another application to signal the completion. In order to do that, the message session must be injected. I am thinking of using the Hangfire.Autofac package to achieve this.
public class JobExecutor : IJobExecutor
{
IMessageSession messageSession;
public JobExecutor(IMessageSession messageSession)
{
this.messageSession = messageSession;
}
public Task DoJob()
{
Console.WriteLine("Job started...");
// do some processing
Thread.Sleep(1000);
Console.WriteLine("Job finished.");
return this.messageSession.Send(new JobCompletedMessage());
}
}
This is where I’m currently stuck because I don’t know how to get the message session and do the injection. Any help would be greatly appreciated. Thank you in advance!