有没有办法挂钩到WebJobs函数执行,所以我们可以为每个函数设置一个范围?像这样的东西: kernel.Bind MyDbContext()ToSelf()InWebJobFunctionScope().; 我想使用Ninject的InScope(),但我不知道在哪里可以找
kernel.Bind< MyDbContext>()ToSelf()InWebJobFunctionScope().;
我想使用Ninject的InScope(),但我不知道在哪里可以找到类似于静态HttpContext.Current的内容,但是对于当前正在运行的WebJob.
我知道这是一个旧的,但我有同样的戏剧.从更新版本的Web作业开始,您可以使用实例和实例方法,并传入自定义IJobActivator实例.这简直太容易了.它与Ninject完美配合.我没见过任何Ninject的例子,所以……
public class MyJobActivator : IJobActivator { protected readonly IKernel _kernel; public MyJobActivator(IKernel kernel) { _kernel = kernel; } public T CreateInstance<T>() { return _kernel.Get<T>(); } } public class MyBindings : NinjectModule { public override void Load() { Bind(typeof(DbContext)).To(typeof(MyEntities)); } } class Program { static void Main() { using (IKernel kernel = new StandardKernel(new MyBindings())) { var jobHostConfiguration = new JobHostConfiguration { JobActivator = new MyJobActivator(kernel) }; var host = new JobHost(jobHostConfiguration); // The following code will invoke a function called ManualTrigger and // pass in data (value in this case) to the function host.Call(typeof(Reminders).GetMethod("ManualTrigger"), new { value = 20 }); } } } public class Reminders { private readonly IMyService _myService; public Reminders(IMyService myService) { _myService = myService; } // This function will be triggered based on the schedule you have set for this WebJob // This function will enqueue a message on an Azure Queue called queue [NoAutomaticTrigger] public async Task ManualTrigger(TextWriter log, int value, TextWriter logger) { try { // process the notification request await _myService.FindAndSendReminders(); await _myService.SaveChangesAsync(); } catch (Exception e) { logger.WriteLine(e.Message); Console.WriteLine(e.Message); throw; } } }
编辑:除了上面我已经看到最近了解到你可能不需要使用host.Call(typeof(Reminders).GetMethod(“ManualTrigger”),至少对于连续的web作业.
您只需使您的Functions类非静态并添加注入构造函数,然后使您的处理方法不是静态的.这是下面的图解.
public class Program { static void Main() { using (IKernel kernel = new StandardKernel(new MyBindings())) { var jobHostConfiguration = new JobHostConfiguration { JobActivator = new MyJobActivator(kernel) }; var host = new JobHost(jobHostConfiguration); // The following code ensures that the WebJob will be running continuously host.RunAndBlock(); } } } public class Functions { private readonly IMyService _myService; public Functions(IMyService myService) { _myService = myService; } public async Task ProcessReminders([QueueTrigger("reminder-requests")] string notificationMessage, TextWriter logger) { try { // process the notification request await _myService.FindAndSendReminders(); await _myService.SaveChangesAsync(); } catch (Exception e) { logger.WriteLine(e.Message); Console.WriteLine(e.Message); throw; } } }
我从我发现的Autofac文章中调整了原始代码
http://www.jerriepelser.com/blog/dedependency-injection-with-autofac-and-webjobs
也可以看看
Dependency injection using Azure WebJobs SDK?
对于连续的webjobs
http://www.ryansouthgate.com/2016/05/10/azure-webjobs-and-dependency-injection/