4

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.

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
sf.
  • 24,512
  • 13
  • 53
  • 58
  • Don't know if you can use it because the `IServiceCollection` object is injected from the apnet core runtime. What about using another ioc container ? https://stackoverflow.com/q/30328775/4167200 – Thomas May 22 '17 at 21:45
  • Cheers. We are already pretty ingrained with the built in IOC so changing is a total last resort. I managed to get something working and have posted my findings – sf. May 22 '17 at 23:27

1 Answers1

8

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();
   }
 }

}

Piotr Kula
  • 9,597
  • 8
  • 59
  • 85
sf.
  • 24,512
  • 13
  • 53
  • 58
  • 3
    Thought I should add a more complete solution since there wasn't much I could find on the net – sf. May 23 '17 at 01:00