Runly jobs use the built-in service container, IServiceProvider, by default. However, any service container that works with .NET Core can be plugged in and used with your jobs.

This guide will walk you through using Autofac to register dependencies in your job application.

Setup

Add a reference to the Autofac.Extensions.DependencyInjection package on nuget:

dotnet add package Autofac.Extensions.DependencyInjection

Then, in your Program.cs where you create the default builder from the JobHost, register your dependencies using Autofac’s ContainerBuilder:

using Autofac;
using Autofac.Extensions.DependencyInjection;

class Program
{
	static async Task Main(string[] args)
	{
		await JobHost.CreateDefaultBuilder(args)
			// call ConfigureContainer instead of ConfigureServices
			.ConfigureContainer<ContainerBuilder>(builder =>
			{
				builder.RegisterType<MyDatabase>()
					.As<IDatabase>()
					.InstancePerLifetimeScope();
			})
			.Build()
			.RunJobAsync();
	}
}

Using Configuration

You can register dependencies using a job configuration class similar to how you would do it with IServiceProvider:

builder.Register(c =>
{
	var config = c.Resolve<MyConfig>();
	return new MyDatabase(config.ConnectionString);
})
.As<IDatabase>()
.InstancePerLifetimeScope();

Using Modules

To follow the pattern of keeping your job dependency registrations near your job, you can break up your registrations based on a job or group of jobs using Autofac modules.

using Autofac;
using Autofac.Extensions.DependencyInjection;

class Program
{
	static async Task Main(string[] args)
	{
		await JobHost.CreateDefaultBuilder(args)
			.ConfigureContainer<ContainerBuilder>(builder =>
			{
				builder.RegisterModule(new MyJobModule());
				builder.RegisterModule(new MyOtherJobModule());
			})
			.Build()
			.RunJobAsync();
	}
}