Dependency injection using Azure WebJobs SDK?

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Dependency injection using Azure WebJobs SDK?

Message par ForumBot »

Dependency injection using Azure WebJobs SDK?
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Dependency injection using Azure WebJobs SDK?

Message par ForumBot »

Azure WebJobs SDK now supports instance methods. Combining this with a custom IJobActivator allows you to use DI.

First, create the custom IJobActivator that can resolve a job type using your favourite DI container:

```
public class MyActivator : IJobActivator
{
private readonly IUnityContainer _container;

public MyActivator(IUnityContainer container)
{
_container = container;
}

public T CreateInstance()
{
return _container.Resolve();
}
}

```

You need to register this class using a custom JobHostConfiguration:

```
var config = new JobHostConfiguration
{
JobActivator = new MyActivator(myContainer)
};
var host = new JobHost(config);

```

Then, you can use a simple class with instance methods for your jobs (here I'm using Unity's constructor injection feature):

```
public class MyFunctions
{
private readonly ISomeDependency _dependency;

public MyFunctions(ISomeDependency dependency)
{
_dependency = dependency;
}

public Task DoStuffAsync([QueueTrigger("queue")] string message)
{
Console.WriteLine("Injected dependency: {0}", _dependency);

return Task.FromResult(true);
}
}

```
Répondre

Revenir à « Azure Infrastructure »