我试图弄清楚如何使用ServiceCollectionfrom 在Azure WebJob中进行依赖注入Microsoft.Extensions.DependencyInjection
例如:
services.AddTransient<IAdminUserLogsService, AdminUserLogsService>();
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何将此服务集合连接到WebJobs JobHostConfiguration.JobActivator可以理解的内容
我的目的是按照默认的AspNet核心Startup.cs方式重新使用我使用此方法设置的默认服务接线.
昨晚搜索后仍然找不到多少.
但经过一番摆弄后,我设法得到了以下内容:
编辑:我添加了一个更完整的实体框架解决方案.我应该注意到我的ASP.Net Core webapp是基于4.6.2而不是纯核心构建的.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
}