In my previous post, I showed how to connect to FTP server via Azure Webjob. In this post, I’m going to show how to inject dependency in Azure Webjob using Unity.
Azure Webjob uses a JobActivator to create instances of job classes. A custom job activator can be used to resolve any dependencies when creating instances. To create a custom job activator, simply create a class that implements the IJobActivator. You can then pass in your favourite DI container, here I’ll be using Unity.
/// <summary> /// The implementation of Webjob unity job activator. /// </summary> public class UnityJobActivator : IJobActivator { /// <summary> /// The unity container. /// </summary> private readonly IUnityContainer container; /// <summary> /// Initializes a new instance of the <see cref="UnityJobActivator"/> class. /// </summary> /// <param name="container"> /// The unity container. /// </param> public UnityJobActivator(IUnityContainer container) { this.container = container; } /// <inheritdoc /> public T CreateInstance<T>() { return this.container.Resolve<T>(); } }
Next, you can create a static class to configure the Unity container. Let’s say we have an interface called IManagerService and its implementation ManagerService that we want to configure in the container. The container configuration class can be implemented as below.
/// <summary> /// The unity configuration for Webjob. /// </summary> public class UnityConfig { /// <summary> /// Gets the configured container. /// </summary> /// <returns> /// The <see cref="IUnityContainer"/>. /// </returns> public static IUnityContainer GetConfiguredContainer() { var container = new UnityContainer(); this.container.RegisterType<IManagerService, ManagerService>(); return container; } }
Then, in Program.cs you need to create a new job host configuration where you can set the custom job activator as the job activator and pass in the container configurations.
static void Main() { var config = new JobHostConfiguration() { JobActivator = new UnityJobActivator(UnityConfig.GetConfiguredContainer()) }; var host = new JobHost(config); host.Call(typeof(Functions).GetMethod("ImportFiles")); // The following code ensures that the WebJob will be running continuously host.RunAndBlock(); }
Finally, you can inject dependencies through instructor of the Function.cs
public class Functions { private readonly IManagerService managerService; public Functions(IManagerService managerService) { this.managerService = managerService; } }