DEV Community

Sanjeevi Subramani
Sanjeevi Subramani

Posted on • Originally published at lkgforit.com on

Implementing Middleware in Bot Framework Composer

Implementing Middleware in Bot Framework Composer

https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-middleware?view=azure-bot-service-4.0

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);
            }
        }
   }

Enter fullscreen mode Exit fullscreen mode

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>();
        }

Enter fullscreen mode Exit fullscreen mode

Thanks Happy Coding :)

Top comments (0)