单例类的Bot框架

时间:2017-05-12 08:41:43

标签: c# singleton botframework

我正在使用恢复cookie做一个主动的机器人。

我有1个单例类,它是一个对象列表。我将单身定义为:

public static MyObj instance = new MyObj();

public List<Objects> thename = null;
public int count { get; set; }

public static MyObj Instance
{
        get
        {
           return instance;
        }
}

然后我有conversationStarter类:

public class ConversationStarter
    {

        public static string resumptionCookie;

        public static async Task Resume()
        {
            var message = ResumptionCookie.GZipDeserialize(resumptionCookie).GetMessage();
            var client = new ConnectorClient(new Uri(message.ServiceUrl));

            using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
            {
                var botData = scope.Resolve<IBotData>();
                await botData.LoadAsync(CancellationToken.None);
                var task = scope.Resolve<IDialogTask>();

                //interrupt the stack
                var dialog = new AlarmDialog();
                task.Call(dialog.Void<object, IMessageActivity>(), null);


                task.PollAsync(CancellationToken.None);

                //flush dialog stack
                await botData.FlushAsync(CancellationToken.None);
            }
        }
    }
}

从RootDialog我有一个定时器,每隔x秒调用一个新的Dialog。 在那个对话框中我做了:

    [Serializable]
    public class NewDialog : IDialog<object>
    {
        public Myobj objList;

        public async Task StartAsync(IDialogContext context)
        {
            objList= Myobj.Instance;


            PromptDialog.Choice(context, this.AfterSelectOption, 
                new string[] { "Stay in this survey", "Get back to where I was" },
                "Hello, you're in the survey dialog. Please pick one of these options");

        }

        private async Task AfterSelectOption(IDialogContext context, IAwaitable<string> result)
        {

            if ((await result) == "Get back to where I was")
            {
                await context.PostAsync("Great, back to the original conversation!");
                context.Done(String.Empty); //Finish this dialog
            }
            else
            {
                await context.PostAsync("I'm still on the survey until you tell me to stop");
                PromptDialog.Choice(context, this.AfterSelectOption, new string[] { "Stay in this survey", "Get back to where I was" }, "Hello, you're in the survey dialog. Please pick one of these options");

            }
        }
    }
}

当我在NewDialog中访问MyObj的实例时,我得到以下异常int ConversationStarter:

Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException: 'invalid need: expected Wait, have None'

在这一行:

 task.PollAsync(CancellationToken.None);

如果我不尝试访问我的单身课程,一切顺利。难道不可能像这样使用单身类吗?

1 个答案:

答案 0 :(得分:0)

这不是实施主动式机器人的方法。如果我没有通过调用PollAsync方法弄错,那么你正在中断对话框堆栈,而没有给它一个恢复点。

我想你应该看看this example。它与您的机器人具有相同的目标,但它使用Autofac。更具体地说是ExternalEvents类。使用IOC容器也比实现Singleton更好。