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

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

问题描述

问题在于 Azure WebJobs SDK 仅支持公共静态方法作为作业入口点,这意味着无法实现构造函数/属性注入.

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 文档/资源中找到有关此主题的任何信息.我遇到的唯一解决方案是基于这篇文章中描述的服务定位器(反)模式 此处.

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 WebJobs SDK 现在支持实例方法.将此与自定义 IJobActivator 结合使用,您可以使用 DI.

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

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

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

然后,您可以为您的作业使用一个带有实例方法的简单类(这里我使用的是 Unity 的构造函数注入功能):

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 WebJobs SDK 进行依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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