c# - 在 Azure Function 中为 Azure 服务总线输出绑定创建自定义转换器
问题描述
我目前正在写这样的服务总线:
[FunctionName("UpdateConfiguration")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] SampleConfiguration config,
[ServiceBus("mytopic" , Connection = "ConnectionStrings:ServiceBusConnectionString")] IAsyncCollector<Message> message,
ILogger log)
{
await message.AddAsync(CreateMessage(config));
return new OkObjectResult(config);
}
public Message CreateMessage<TObject>(TObject body) where TObject : class, new()
{
string jsonString = JsonSerializer.Serialize(body);
byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonString);
Message message = new (jsonBytes)
{
ContentType = "application/json",
Label = "ConfigurationUpdated",
To = Environment.MachineName
};
return message;
}
我想通过实现这里描述的自定义转换器来简化这一点。我已经查看了Azure Functions Service Bus Extensions的源代码,但一切似乎都是内部的,所以我不确定是否可以添加自定义绑定,我可以在其中放置用于序列化消息的代码。
有没有办法添加这个自定义转换器:
public class ObjectToJsonMessageConverter<TObject> : IConverter<TObject, Message> where TObject: class, new()
{
public Message Convert(TObject input)
{
string jsonString = JsonSerializer.Serialize(body);
byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonString);
Message message = new(jsonBytes)
{
ContentType = "application/json",
Label = "ConfigurationUpdated",
To = Environment.MachineName
};
return message;
}
}
那我能做到吗?
[ServiceBus("mytopic" , Connection = "ConnectionStrings:ServiceBusConnectionString")] IAsyncCollector<SampleConfiguration> configuration,
ILogger log)
{
await message.AddAsync(config);
return new OkObjectResult(config);
}
我之所以要这样做是因为如果有可能使用自定义输出绑定,我不想将 MessageFactory 注入我的每个函数。但我不想分叉完整的服务总线绑定来实现这一点。
解决方案
推荐阅读
- r - 在 Linux 上的 Azure 上部署 R (centos 8.2.2004)
- javascript - 将数据从 ngFor 传递到模态
- php - PHP DOMDocument:如果没有 nodeValue,则获取 Null
- google-apps-script - 我可以使用脚本复制和重命名 Google 表格中的工作表,并将当前数据作为选项卡名称吗?
- java - java,如何计算gregorion年(1583到4000之间的年份)中最频繁的一天?
- python-3.x - imageio(imsave)ValueError:最大值==最小值,给定dtype不明确
- java - 带有 RestController、Component 和 Configuration 注释的 bean 同时违反了 SRP?
- sql - 基于返回值的 SQL 更改命名为 AS 列
- android - Android Studio,模拟器进程被杀死
- java - AR核心/是否可以同时加载两个不同的2D纹理?