Inject message session into Hangfire job

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!

Hi @adoloca,

NServiceBus integrates with the DI infrastructure provided by Generic Host. An instance of IMessageSession should be available in the DI after the host starts.

I don’t have much experience using Hangfire but the approach you mention sounds reasonable i.e. suing Autofac both for the host and Hangfire JobExecutor

Cheers,
Tomek