【问题标题】:V2 Azure Function dependency injection and Microsoft.Azure.WebJobs.BinderV2 Azure 函数依赖注入和 Microsoft.Azure.WebJobs.Binder
【发布时间】:2019-07-27 06:34:18
【问题描述】:

我已经成功地为我自己的自定义服务使用了依赖注入,如 here 所记录的那样。

我想要在我的自定义服务中使用框架作为参数注入到 Azure Functions 的 Binder。 用作函数参数的示例:

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, Binder binder, TraceWriter log)

我尝试将 Binder 作为参数添加到我的服务构造函数并让框架创建我的服务实例,但传入的 Binder 始终为空。

我的服务构造函数:

public MyService(Binder binder)

这样注册:

builder.Services.AddSingleton<IMyService, MyService>();

有谁知道这是否可行,如果可以,我做错了什么?

【问题讨论】:

  • shavua tov,你试过我的例子吗?

标签: azure azure-functions


【解决方案1】:

您首先必须创建一个允许您读/写的类:

   public static class Bindor
    {
        public static async Task<string> ReadFromBlob(string path, Binder binder, string connection)
        {
            var attributes = new Attribute[]
            {
                    new BlobAttribute(path),
                    new StorageAccountAttribute(connection)
            };

            using (var reader = await binder.BindAsync<TextReader>(attributes))
            {
                return await reader.ReadToEndAsync();
            }
        }

        public static async Task BindToBlob(string path, Binder binder, object payload, string connection)
        {
            var attributes = new Attribute[]
            {
                    new BlobAttribute(path),
                    new StorageAccountAttribute(connection)
            };
            using (var writer = await binder.BindAsync<TextWriter>(attributes))
            {
                writer.Write(payload);
            }
        }
    }

然后你会在你的函数中包含Binder binder 作为参数(就像你正在做的那样)。

示例用法如下:

//path would be your path to the blob (including the container)
//binder is the parameter from your function signature
//sorry about the confusing naming, Bindor is the class we created, whereas Binder is the functions class
await Bindor.BindToBlob(path, binder, "my payload", connection);

【讨论】:

  • 这绝对有效,如果它是唯一的选择,我会使用它。
  • 我是否应该假设因为您将 Bi​​nder 作为函数参数传递,所以在创建我的服务期间使用依赖注入不是一个选项?如果我的服务可以在创建时接收活页夹并只存储对它的引用,那将会更干净。我没有为此查看框架源代码,因此可能有正当理由将活页夹限定为函数调用。
  • 我不知道。使用Binder 的方式不同于使用新添加的功能 dependency injenction 用于 azure 函数(此功能可能是在大约 6 个月前添加的)
猜你喜欢
  • 2020-03-09
  • 2023-03-03
  • 2017-11-07
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
相关资源
最近更新 更多