Implementing Middleware in Bot Framework Composer

Implementing Middleware in Bot Framework Composer

How to create a Middleware for Bot Framework Composer | Implement DotnetCore Middleware concept in Bot Framework composer

Sanjeevi Subramani's photo
Sanjeevi Subramani
·Dec 28, 2021·

2 min read

Subscribe to our newsletter and never miss any upcoming articles

Play this article

Table of contents

  • Implementing Middleware in Bot Framework Composer

Implementing Middleware in Bot Framework Composer

Handling state in middleware

A common method to save state is to call the save changes method at the end of the turn handler. Here is a diagram with a focus on the call.

image.png

The problem with this approach is that any state updates made from some custom middleware that happens after the bot's turn handler has returned will not be saved to durable storage. The solution is to move the call to the save changes method to after the custom middleware has completed by adding an instance of the auto-save changes middleware to the beginning of the middleware stack, or at least before any of the middleware that might update state. The execution is shown below.

image.png

Add the state management objects that will need updating to a bot state set object, and then use that when you create your auto-save changes middleware.

Creating Middleware for Composer Bot

  • Create a class file
  • Inherit this interface - Microsoft.Bot.Builder.IMiddleware
  • Implement OnTurnAsync Method like below code sample
  • You will have access to context, Activity and other stuffs you do in bot framework library implementations
  • To Access config values use this config_val.AppsettingKeyName
  • To Access user Activity use context.Activity
  • To Access user message use context.Activity.Text
  • To Access config values use this config_val.AppsettingKeyName if the appsettings json file contains the key name as 'AppsettingKeyName'

    public class SampleMiddleware : Microsoft.Bot.Builder.IMiddleware
    {
        private readonly IConfiguration config_val;

        public SampleMiddleware (IConfiguration iconfig)
        {
            config_val = iconfig;
        }

        public virtual async Task OnTurnAsync(ITurnContext context, NextDelegate nextTurn, CancellationToken cancellationToken)
        {
            // Condition to filter based on message or event
            if (context.Activity.Type == "message")
            {
                    var userText = context.Activity.Text;
                    // Do some stuff here with Activity or user input text

                    // To Access config values use this 
                    config_val.AppsettingKeyName

                    // use below code if you want to run the default flow happens remove below code if / 
                    //you don't want to trigger bot action and end the turn.
                    await nextTurn(cancellationToken).ConfigureAwait(false);
            }
        }
   }

Initiate the Middleware in Startup of Composer Bot

Initialize the middleware in the startup.cs file inside the ConfigureServices method like below code snippet.


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();
            services.AddBotRuntime(Configuration);

            //code to initialize middleware
            services.AddSingleton<IMiddleware, SampleMiddleware>();
        }

Thanks Happy Coding :)

Did you find this article valuable?

Support LKG for IT by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this