Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure WebJob and wiring up IServiceCollecton from Microsoft.Extensions.DependencyInjection

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.

like image 492
sf. Avatar asked Oct 19 '25 04:10

sf.


1 Answers

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

}

like image 92
sf. Avatar answered Oct 21 '25 18:10

sf.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!