在静态函数范围内使用WebJobs对DbContext进行依赖注入Ninject

时间:2016-04-12 17:02:46

标签: dependency-injection azure-webjobs azure-webjobssdk

有没有办法挂钩WebJobs函数执行,所以我们可以为每个函数设置一个范围?像这样:

kernel.Bind<MyDbContext>().ToSelf().InWebJobFunctionScope();

我想使用来自Ninject的InScope(),但我不知道在哪里可以找到与静态HttpContext.Current类似的内容,但对于当前正在运行的WebJob。

1 个答案:

答案 0 :(得分:8)

我知道这是一个旧的,但我有同样的戏剧。从更新版本的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/