The following example shows how to set up Dependency Injection using Ninject as an IoC container.
First add a CustomModule class to your WebJob project, and add any dependency bindings there.
public class CustomModule : NinjectModule
{
public override void Load()
{
Bind<IMyInterface>().To<MyService>();
}
}
Then create a JobActivator class:
class JobActivator : IJobActivator
{
private readonly IKernel _container;
public JobActivator(IKernel container)
{
_container = container;
}
public T CreateInstance<T>()
{
return _container.Get<T>();
}
}
When you set up the JobHost in the Program class' Main function, add the JobActivator to the JobHostConfiguration
public class Program
{
private static void Main(string[] args)
{
//Set up DI
var module = new CustomModule();
var kernel = new StandardKernel(module);
//Configure JobHost
var storageConnectionString = "connection_string_goes_here";
var config = new JobHostConfiguration(storageConnectionString) { JobActivator = new JobActivator(kernel) };
//Pass configuration to JobJost
var host = new JobHost(config);
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
}
Finally in the Functions.cs class, inject your services.
public class Functions
{
private readonly IMyInterface _myService;
public Functions(IMyInterface myService)
{
_myService = myService;
}
public void ProcessItem([QueueTrigger("queue_name")] string item)
{
_myService .Process(item);
}
}