Azure Function Binding Declaration Types
If you are familiar with azure function you may already know there are many types of binding. If you are new for azure function bindings you can read more details here.
When adding an output binding for your function code there are two ways of doing it.
1. Declarative Binding
2. Imperative Binding
Declarative Binding
Suppose we have a CosmosDB output Binding. In Declarative Binding we can specify the binding details in the Run method parameter. This is the most common way most of us using
public static class WriteOneDoc { [FunctionName("WriteOneDoc")] public static void Run( [QueueTrigger("todoqueueforwrite")] string queueMessage, [CosmosDB( databaseName: "ToDoItems", collectionName: "Items", ConnectionStringSetting = "CosmosDBConnection")]out dynamic document, ILogger log) { document = new { Description = queueMessage, id = Guid.NewGuid() }; log.LogInformation($"C# Queue trigger function inserted one row"); log.LogInformation($"Description={queueMessage}"); } }
Imperative Binding
Problem in declarative binding comes when we want to pass the collection name dynamically.
For an example: Based on the data we get from the queue message, we need to decide to which collection the data shout be saved to. That cannot be achieved with declarative binding. Solution is imperative binding. In this we can specify the output binding inside the method execution code as below.
In this Code “Binder” parameter is declared in the method. But the values for the binder been assigned runtime. So we can specify cosmos connection data dynamically during runtime.
[FunctionName("WriteOneDoc")] public async Task Run( [QueueTrigger("todoqueueforwrite")] string queueMessage, Binder binder, ILogger log) { var collectionName = "tasks"; var attribute = new DocumentDBAttribute("ToDoItems", collectionName) { CreateIfNotExists = true, ConnectionStringSetting = "CosmosDBConnection" }; var collector = await binder.BindAsync<IAsyncCollector<dynamic>>(attribute); await collector.AddAsync( new { Description = queueMessage, id = Guid.NewGuid() }); } }
Hope this helps.
Happy Coding !!!!
Thank you for sharing your thoughts and knowledge on this topic.
ReplyDeleteAzure Development Training in Hyderabad