依赖注入的Azure使用SDK WebJobs? [英] Dependency injection using Azure WebJobs SDK?

查看:156
本文介绍了依赖注入的Azure使用SDK WebJobs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是,在Azure SDK WebJobs只支持公共静态方法作为工作的切入点,这意味着没有实现构造/物业注入方式。

The problem is that the Azure WebJobs SDK supports only public static methods as job entry-points which means there is no way of implementing constructor/property injection.

我无法找到有关此主题的官方WebJobs SDK文档/资源的任何东西。我遇到的唯一的解决方案是基于服务定位器对这个职位<所描述的(反)模式href=\"http://www.jerriepelser.com/blog/using-autofac-and-common-service-locator-with-azure-webjobs\">here.

I am unable to find anything about this topic in official WebJobs SDK documentation/resources. The only solution that I came across is based on service locator (anti) pattern described on this post here.

有没有用适当的依赖注入基于Azure的WebJobs SDK项目的好办法?

Is there a good way to use "proper" dependency injection for projects based on Azure WebJobs SDK?

推荐答案

的Azure SDK WebJobs现在支持实例方法。使用自定义IJobActivator结合起来,允许您使用DI

Azure WebJobs SDK now supports instance methods. Combining this with a custom IJobActivator allows you to use DI.

首先,创建自定义IJobActivator可以使用自己喜欢的DI容器解决作业类型:

First, create the custom IJobActivator that can resolve a job type using your favourite DI container:

public class MyActivator : IJobActivator
{
    private readonly IUnityContainer _container;

    public MyActivator(IUnityContainer container)
    {
        _container = container;
    }

    public T CreateInstance<T>()
    {
        return _container.Resolve<T>();
    }
}

您需要使用自定义JobHostConfiguration注册这个类:

You need to register this class using a custom JobHostConfiguration:

var config = new JobHostConfiguration
{
    JobActivator = new MyActivator(myContainer)
};
var host = new JobHost(config);

然后,您可以使用与实例方法的简单类为作业(在这里我使用统一的构造注入功能):

Then, you can use a simple class with instance methods for your jobs (here I'm using Unity's constructor injection feature):

public class MyFunctions
{
    private readonly ISomeDependency _dependency;

    public MyFunctions(ISomeDependency dependency)
    {
        _dependency = dependency;
    }

    public Task DoStuffAsync([QueueTrigger("queue")] string message)
    {
        Console.WriteLine("Injected dependency: {0}", _dependency);

        return Task.FromResult(true);
    }
}

这篇关于依赖注入的Azure使用SDK WebJobs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆