Created
April 3, 2023 14:50
-
-
Save tomkuijsten/87d777a0896972cc068cc0e5d4d688f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Concurrent; | |
namespace ServiceBus.Extensions.Bindings.MessageActions; | |
/// <summary> | |
/// Runs on every request and passes the function context (e.g. Http request and host configuration) to a value provider. | |
/// </summary> | |
public class MessageActionsExtendedBinding : IBinding | |
{ | |
private static ConcurrentDictionary<string, string> _functionNameWithQueueOrTopicNameCache = new ConcurrentDictionary<string, string>(); | |
private static string GetQueueOrTopicNameFromServicebusTrigger(string functionName) | |
{ | |
if (_functionNameWithQueueOrTopicNameCache.TryGetValue(functionName, out var queueOrTopicName)) | |
{ | |
return queueOrTopicName; | |
} | |
var funcMethodInfo = AppDomain.CurrentDomain | |
.GetAssemblies() | |
.SelectMany(x => x.GetTypes()) | |
.SelectMany(t => t.GetMethods()) | |
.FirstOrDefault(m => m.GetCustomAttributes<FunctionNameAttribute>(false).Any(a => a.Name == functionName)); | |
if (funcMethodInfo == null) | |
{ | |
throw new InvalidOperationException("Could not match functionName with a trigger."); | |
} | |
queueOrTopicName = funcMethodInfo | |
.GetParameters() | |
.SelectMany(p => p.GetCustomAttributes<ServiceBusTriggerAttribute>(false)) | |
.Select(a => a.QueueName ?? a.TopicName) | |
.FirstOrDefault(q => !string.IsNullOrWhiteSpace(q)); | |
if (string.IsNullOrEmpty(queueOrTopicName)) | |
{ | |
throw new InvalidOperationException("Could not find a servicebustrigger for the function."); | |
} | |
_functionNameWithQueueOrTopicNameCache.TryAdd(functionName, queueOrTopicName); | |
return queueOrTopicName; | |
} | |
public Task<IValueProvider> BindAsync(BindingContext context) | |
{ | |
var queueOrTopicName = GetQueueOrTopicNameFromServicebusTrigger(context.ValueContext.FunctionContext.MethodName); | |
// Get the HTTP request | |
var actions = context.BindingData["MessageActions"] as ServiceBusMessageActions; | |
var client = context.BindingData["Client"] as ServiceBusClient; | |
return Task.FromResult((IValueProvider)new MessageActionsExtendedValueProvider(actions, client, queueOrTopicName)); | |
} | |
public bool FromAttribute => true; | |
public Task<IValueProvider> BindAsync(object value, ValueBindingContext context) | |
{ | |
return null; | |
} | |
public ParameterDescriptor ToParameterDescriptor() => new ParameterDescriptor(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment