c# - 从 Bot 类外部访问 BotState 变量

标签 c# azure asp.net-core botframework

在机器人类中,我们创建 ConversationState 和 UserState 对象,我们可以使用其访问器访问它们并在它们上创建属性,然后保存我们存储的数据。

但是,如果我想从 Bot 类调用的 Dialog 访问数据,我该如何做同样的事情呢?我知道我可以使用 BeginDialogAsync 选项参数通过 Context 传递对象。我如何传递其中两个而不是仅一个以及如何将它们放入对话框类中?

有没有一种方法可以访问 ConversationState 和 UserState,而不必在对话框之间传递它们?

public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
    await base.OnTurnAsync(turnContext, cancellationToken);

    // Save any state changes that might have occured during the turn.
    await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
    await UserState.SaveChangesAsync(turnContext, false, cancellationToken);
}

protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
    Logger.LogInformation("Running dialog with Message Activity.");

    // Run the Dialog with the new message Activity.
    await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>("DialogState"), cancellationToken);
}

在 CoreBot 示例的这个函数中,我们可以看到 ConversationState 和 UserState 已保存,但它们在其他任何地方都没有修改,并且在第二个函数中,在子对话框中创建了一个 DialogState 属性,但它我看到的也没有被使用?有人可以解释为什么创建它们以及如何从刚刚调用的对话框内部访问它们吗?

最佳答案

您可以使用依赖注入(inject)。

 public class UserStateClass
 {
        public string name { get; set; }
 }

 public class YourDialog : ComponentDialog
 {
        private readonly IStatePropertyAccessor<UserStateClass> _userStateclassAccessor;

        public YourDialog(UserState userState)
            : base(nameof(YourDialog))
        {
            _userProfileAccessor = userState.CreateProperty<UserStateClass>("UserProfile");

            WaterfallStep[] waterfallSteps = new WaterfallStep[]
            {
                FirstStepAsync,
            };
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
        }

        private async Task<DialogTurnResult> FirstStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var userstate = await _userStateclassAccessor.GetAsync(stepContext.Context, () => new UserStateClass(), cancellationToken);

            userstate.name = "pepe";
            return await stepContext.EndDialogAsync();
        }
 }

关于c# - 从 Bot 类外部访问 BotState 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57710404/

相关文章:

Azure api 管理 发布者门户 为 Bi 提供动力?

c# - HttpGet 在 Mvc 核心 2.0 中返回 404

c# - 帮助我理解 c# 中的代码片段

c# - 项目引用另一个项目的 obj 文件夹中的 dll - 有时编译有时不编译

c# - Mono 编译错误 - 无法从程序集 'System.Runtime.CompilerServices.ReferenceAssemblyAttribute' 加载类型 'System'

c# - 将数据从 ModelBinder 传递到自定义 InputFormatter

javascript - 如何在 Aurelia 中注入(inject)/替换部分 View 和 View 模型

c# - .NET 中的消息代理服务器 (CoreCLR/DNX)

windows - Azure 云服务 阻止所有公共(public)访问(有异常(exception))

azure - BASH bug 对 Azure 网站、云服务和 SQL 数据库的影响?