首页 > 解决方案 > 在 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 注入我的每个函数。但我不想分叉完整的服务总线绑定来实现这一点。

标签: c#azure.net-coreazure-functionsazureservicebus

解决方案


推荐阅读