Как получить доступ к хранилищу без внедрения зависимостей в каждом диалоге в botframework V4 - PullRequest
0 голосов
/ 08 июля 2019

Здравствуйте, я пытаюсь перенести мой код из дизайна Bot Framework v4 в январе прошлого года в новый дизайн. В предыдущем коде я могу просто назвать этот код:

var userstate = await (stepContext.Context.TurnState["BasicAccessors"] as BasicAccessors).BasicUserStateAccessor.GetAsync(stepContext.Context);

в каждом диалоговом окне для доступа к хранилищу, но я не могу этого сделать, и мне нужно каждый раз вводить зависимости. Как реализовать этот код на этом новом дизайне? Спасибо.

    namespace BasicBot
    {
    public class BasicAccessors
    {
        public BasicAccessors(ConversationState conversationState, UserState userState)
        {
            ConversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            UserState = userState ?? throw new ArgumentException(nameof(userState));
        }

        public static string DialogStateAccessorName { get; } = $"{nameof(BasicAccessors)}.DialogState";

        public static string BasicUserStateAccessorName { get; } = $"{nameof(BasicAccessors)}.BasicUserState";

        public IStatePropertyAccessor<BasicUserState> BasicUserStateAccessor { get; internal set; }

        public IStatePropertyAccessor<DialogState> DialogStateAccessor { get; internal set; }

        public ConversationState ConversationState { get; }

        public UserState UserState { get; }
    }
}

код бота:

 public class DialogBot<T> : ActivityHandler where T : Dialog
{
    protected readonly Dialog Dialog;
    protected readonly BotState ConversationState;
    protected readonly BotState UserState;
    protected readonly ILogger Logger;

    public DialogBot(ConversationState conversationState, UserState userState, T dialog, ILogger<DialogBot<T>> logger)
    {
        ConversationState = conversationState;
        UserState = userState;
        Dialog = dialog;
        Logger = logger;
    }

    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.
        var userStateAccessors = UserState.CreateProperty<BookingDetails>(nameof(BookingDetails));
        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.Run(turnContext, ConversationState.CreateProperty<DialogState>("DialogState"), cancellationToken);
    }
}

запуск:

  public class Startup
{
    public Startup()
    {
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // Create the credential provider to be used with the Bot Framework Adapter.
        services.AddSingleton<ICredentialProvider, ConfigurationCredentialProvider>();

        // Create the Bot Framework Adapter with error handling enabled.
        services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

        // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
        services.AddSingleton<IStorage, MemoryStorage>();

        // Create the User state. (Used in this bot's Dialog implementation.)
        services.AddSingleton<UserState>();

        // Create the Conversation state. (Used by the Dialog system itself.)
        services.AddSingleton<ConversationState>();

        services.AddSingleton<BasicAccessors>();

        // The Dialog that will be run by the bot.
        services.AddSingleton<MainDialog>();

        // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
        services.AddTransient<IBot, DialogBot<MainDialog>>();


    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseDefaultFiles();
        app.UseStaticFiles();

        //app.UseHttpsRedirection();
        app.UseMvc();
    }
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...