c# - 将内部类注入(inject) Azure WebJob 函数

标签 c# azure unity-container azure-webjobs

有什么办法可以默认Functions WebJob 项目中的类为 internal ?我们使用作业激活器通过 Unity 注入(inject)一些依赖项,这些依赖项是 internal ,这要求 Functions类也为internal 。运行网络作业时,我们看到以下错误:

No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).

当我们创建所有依赖项 public ,它工作正常,所以我知道我的触发器或作业主机配置没有任何问题。

这是我的程序类:

class Program
{
    static void Main()
    {
        var config = new JobHostConfiguration
        {
            JobActivator = new Activator(new UnityContainer())
        };
        config.UseServiceBus();
        var host = new JobHost(config);
        host.RunAndBlock();
    }
}

这是我的 Functions 类的简化版本:

internal class Functions
{
    private readonly IMyInternalDependency _dependency;

    public Functions(IMyInternalDependency dependency)
    {
        _dependency = dependency;
    }

    public function DoSomething([ServiceBusTrigger("my-queue")] BrokeredMessage message)
    {
        // Do something with the message
    }
}

最佳答案

您必须将Functions 类公开。这似乎就是 Azure WebJobs 的工作原理。您不需要公开公开具体的内部类。只是接口(interface):

public interface IDoStuffPublically
{
    void DoSomething();
}

interface IDoStuffInternally
{
    void DoSomething();
    void DoSomethingInternally();
}

class DoStuff : IDoStuffPublically, IDoStuffInternally
{
    public void DoSomething()
    {
        // ...
    }

    public void DoSomethingInternally()
    {
        // ...
    }
}

然后是你的Functions类:

public class Functions
{
    public Functions(IDoStuffPublically stuff)
    {
        _stuff = stuff;
    }

    private IDoStuffPublically _stuff;

    // ...
}

Unity 会做这样的事情:

var job = new Functions(new DoStuff());
<小时/>

戴夫评论道:

It's frustrating that I cannot simply set the internals visible to the WebJob SDK...

也许能够完成这个...miiiiiiiiiight能够...

程序集或可执行文件有一种方法可以授予另一个程序集访问内部成员的权限。我之前已经在类库上完成了此操作,以允许我的单元测试调用类上的内部方法,作为设置单元测试的一部分。

如果您知道 Azure WebJobs 中的哪个程序集实际创建了 Functions 类的实例,以及调用该类上的方法的程序集,则可以将这些程序集列入白名单。

破解AssemblyInfo.cs并添加一行或多行:

[assembly: InternalsVisibleTo("Microsoft.Azure.Something.Something")]

引用:InternalsVisibleToAttribute class

相关阅读:.Net Tips – using InternalsVisibleTo attribute to help testing non-public methods

不过,我不确定您需要添加哪些程序集。

关于c# - 将内部类注入(inject) Azure WebJob 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37996782/

相关文章:

c# - 不能将 .length 属性与 IronJS 和 ArrayObject 一起使用

azure - 使用逻辑应用将 n 个文件从 Azure Datalake 复制到 SFTP 位置

Azure 应用服务错误 : Reply URL specified in the request does not match the reply URLs configured for the application

azure - 将 SAS token 重写(附加)到 azure cdn 中的 url

c# - 无法安装 NuGet 包

.net - 统一与自定义依赖注入(inject)?

c# - 如何注册所有类型的接口(interface)并统一获取它们的实例?

c# - 从数据库表中查找数据

c# - 在 Windows Azure 中部署 WCF 应用程序

c# - 将日期时间格式更改为 "yyyy-mm-dd"