如何在Botframework中向瀑布步注入依赖性

时间:2019-04-04 20:21:44

标签: asp.net-core .net-core botframework

我需要从botframework中的WaterfallStep中写入CosmosDB,如何注入依赖项,WaterfallStep是静态委托。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以通过构造函数注入来注入DbContext。

  1. 注册DbContext

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(option =>
            option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        //your rest code
    }
    
  2. 注入DbContext

    public class MultiTurnPromptsBot : IBot
    {
        private readonly ApplicationDbContext _context;
        private const string WelcomeText = "Welcome to MultiTurnPromptBot. This bot will introduce multiple turns using prompts.  Type anything to get started.";
    
        private readonly MultiTurnPromptsBotAccessors _accessors;
    
        private DialogSet _dialogs;
    
        public MultiTurnPromptsBot(
            MultiTurnPromptsBotAccessors accessors
            , ApplicationDbContext context)
        {
            _accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));
            _context = context;
            // The DialogSet needs a DialogState accessor, it will call it when it has a turn context.
            _dialogs = new DialogSet(accessors.ConversationDialogState);
    
            // This array defines how the Waterfall will execute.
            var waterfallSteps = new WaterfallStep[]
            {
                NameStepAsync,
                NameConfirmStepAsync,
            };
    
            // Add named dialogs to the DialogSet. These names are saved in the dialog state.
            _dialogs.Add(new WaterfallDialog("details", waterfallSteps));
            _dialogs.Add(new TextPrompt("name"));
        }        
    
    
        private async Task<DialogTurnResult> NameConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Get the current profile object from user state.
            var userProfile = await _accessors.UserProfile.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);
    
            // Update the profile.
            userProfile.Name = (string)stepContext.Result;
            _context.Add(new User { Name = userProfile.Name });
            _context.SaveChanges();
            // We can send messages to the user at any point in the WaterfallStep.
            await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Thanks {stepContext.Result}."), cancellationToken);
    
            // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
            return await stepContext.PromptAsync("confirm", new PromptOptions { Prompt = MessageFactory.Text("Would you like to give your age?") }, cancellationToken);
        }        
    }