Botframework如何根据传入请求在启动时更改表存储连接字符串

时间:2019-02-06 13:51:32

标签: c# .net-core botframework azure-bot-service state-management

我正在使用与LUIS集成的BotFramework版本(v4)。在 startup.cs 文件的 ConfigureServices(IServiceCollection服务)方法中,我在中间件中分配存储和LUIS。下面是示例代码。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(configuration);

    services.AddBot<ChoiceBot>(options =>
    {    
        options.CredentialProvider = new ConfigurationCredentialProvider(configuration);
        var (luisModelId, luisSubscriptionKey, luisUri) = GetLuisConfiguration(configuration, "TestBot_Dispatch");//
        var luisModel = new LuisModel(luisModelId, luisSubscriptionKey, luisUri);
        var luisOptions = new LuisRequest { Verbose = true };
        options.Middleware.Add(new LuisRecognizerMiddleware(luisModel, luisOptions: luisOptions));

        //azure storage emulater
        //options.Middleware.Add(new ConversationState<Dictionary<string, object>>(new AzureTableStorage("UseDevelopmentStorage=true", "conversationstatetable")));

        IStorage dataStore = new AzureTableStorage("DefaultEndpointsProtocol=https;AccountName=chxxxxxx;AccountKey=xxxxxxxxx;EndpointSuffix=core.windows.net", "TableName");

        options.Middleware.Add(new ConversationState<Dictionary<string,object>>(new MemoryStorage()));
        options.Middleware.Add(new UserState<UserStateStorage>(dataStore));
    }
}

我的机器人将收到来自不同角色(例如,管理员,销售等)的用户的请求。我想根据从传入角色提取的角色来更改传递给中间件的表存储连接字符串请求。我将从用户名中查询数据库来获得用户角色,该用户名是从传入请求的当前TurnContext对象中提取的。我可以通过 OnTurn 方法执行此操作,但是由于这些已在中间件中声明,因此我想在中间件本身进行初始化时更改它们。

1 个答案:

答案 0 :(得分:0)

在.NET Core中,Startup逻辑仅在启动时执行一次。

如果我对您的理解正确,那么您需要做的是:在运行时,在多个存储提供者之间进行切换,根据您的情况,这些存储提供者通过其基础连接字符串来区分。

没有任何“可用的框”为您启用此方案,但是可以使用正确的扩展点并为您自己编写正确的管道。具体来说,您可以在IStatePropertyAccessor<T>层提供自定义的抽象,并且您的上游代码将继续在该级别的抽象上工作,并且更加明智。

Here's an implementation I've started that includes something I'm calling the ConditionalStatePropertyAccessor。它允许您创建一种组合IStatePropertyAccessor<T>,该组合同时配置有默认/后备实例以及 N 个其他实例,这些实例配有选择器功能,使他们可以查看传入的ITurnContext,并根据转弯任何部分的一些细节,指示该实例应用于转弯范围。 Take a look at the tests and you can see how I configure a sample that chooses an implementation based on the ChannelId for example.

此刻我有点忙,暂时无法发货,但我打算打包并最终发货。但是,如果您认为这会有所帮助,请随时复制代码以供自己使用。