Reputation: 25518
I'm trying to figure out how to do dependency injection in an Azure WebJob using a ServiceCollection
from Microsoft.Extensions.DependencyInjection
E.g.:
services.AddTransient<IAdminUserLogsService, AdminUserLogsService>();
I can't quite figure out how to wire up this service collection into something that the WebJobs JobHostConfiguration.JobActivator
can understand
My intention is to re-use the default service wiring I've setup with this method as per the default AspNet core Startup.cs
way.
Upvotes: 4
Views: 2148
Reputation: 25518
Still wasn't able to find much after searching around last night.
But after a bit of fiddling, I managed to get something working with the following:
EDIT: I've added a more complete solution with Entity Framework. I should note that my ASP.Net Core webapp is built upon 4.6.2 instead of pure core.
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.ServiceBus;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
namespace Settlements.WebJob
{
public class ServiceJobActivator : IJobActivator
{
IServiceProvider _serviceProvider;
public ServiceJobActivator(IServiceCollection serviceCollection) : base()
{
_serviceProvider = serviceCollection.BuildServiceProvider();
}
public T CreateInstance<T>()
{
return _serviceProvider.GetRequiredService<T>();
}
}
class Program
{
static void Main()
{
var config = new JobHostConfiguration();
var dbConnectionString = Properties.Settings.Default.DefaultConnection;
var serviceCollection = new ServiceCollection();
// wire up your services
serviceCollection.AddTransient<IThing, Thing>();
// important! wire up your actual jobs, too
serviceCollection.AddTransient<ServiceBusJobListener>();
// added example to connect EF
serviceCollection.AddDbContext<DbContext>(options =>
options.UseSqlServer(dbConnectionString ));
// add it to a JobHostConfiguration
config.JobActivator = new ServiceJobActivator(serviceCollection);
var host = new JobHost(config);
host.RunAndBlock();
}
}
}
Upvotes: 8