c# - 从 Bot 类外部访问 BotState 变量
问题描述
在机器人类中,我们创建 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
中,在子对话框中创建了一个属性,但我可以看到它也没有使用?有人可以解释为什么创建它们以及如何从刚刚调用的 Dialog 内部访问它们吗?
解决方案
您可以使用依赖注入。
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();
}
}
推荐阅读
- office-js - Outlook 插件中 SSO 的可用性
- javascript - 字段名称在 JSON 中,但数据表无法识别?
- java - 在 liferay 中创建新的 portlet pulgin 时出错
- kdb - 正则表达式左加入 KDB
- reactjs - 使用 Typescript 反应 Redux-Thunk
- dart - 如何检查用户日期和时间是否在颤振中设置正确
- php - IMAP 库:使用 lumen 从 Outlook 电子邮件帐户获取所有电子邮件
- git - 在 Windows 10 上激活 ssh-agent 的 VSCode
- jenkins - 如何通过脚本从 Jenkins 中的 Global Builds Stats Plugin 中提取信息
- javascript - 最长夜晚的最佳搜索算法 - Javascript