Reputation: 467
I am trying to add middleware into echo bot, that converts message into lower cases.
I have created Middleware class that inherits from IMiddleware
public class MiddlewareOne : IMiddleware
{
public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default)
{
if(turnContext.Activity.Type == ActivityTypes.Message)
{
Debug.WriteLine(turnContext.Activity.Text);
turnContext.Activity.Text = turnContext.Activity.Text.ToLower();
await next(cancellationToken);
Debug.WriteLine(turnContext.Activity.Text);
}
else
{
await next(cancellationToken);
}
}
}
}
Now I am trying to add it into Startup.cs file. I found somewhere it should be added as Transient.
services.AddTransient<MiddlewareOne>();
Still, it's not working. I think MiddlewareOne class is okay, but how should I configure it in Startup.cs file?
Thank you
Upvotes: 3
Views: 1243
Reputation: 622
You have to register the middleware in your BotFrameworkAdapter descendant (e.g. BotFrameworkHttpAdapter) by calling the Use method in constructor. You can pass the middleware as a constructor parameter and DI will take care of activation.
An example (made without VS assistance)
public class MyAdapter : BotFrameworkHttpAdapter
{
public MyAdapter(MiddlewareOne mw1, IConfiguration configuration, ILogger<BotFrameworkHttpAdapter> logger)
: base(configuration, logger)
{
Use(mw1);
// other code..
}
}
Upvotes: 3