【发布时间】:2018-10-30 14:44:42
【问题描述】:
我正在使用 Azure 机器人服务和 QnAMaker 开发一个新的聊天机器人。我们正在使用 BotBuilder 中间件(包括自定义中间件)来定制机器人行为。
其中一个中间件将调用 Azure 函数,我想将新的 HttpClientFactory 功能与自定义中间件一起使用 - 但这需要依赖注入。
如何像使用常规 .NET Core 中间件一样在 BotBuilder 中间件中使用依赖注入?
当您查看 Startup.cs 中的机器人配置时,您会发现它需要您new机器人依赖:
services.AddHttpClient<MyFunctionClient>(client =>
{
client.BaseAddress = new Uri(mySettings.GetValue<string>("myFunctionUrl"));
client.DefaultRequestHeaders.Add("x-functions-key", mySettings.GetValue<string>("myFunctionKey"));
});
services.AddBot<QnAMakerBot>(options =>
{
options.CredentialProvider = new ConfigurationCredentialProvider(Configuration);
options.ConnectorClientRetryPolicy = new RetryPolicy(
new BotFrameworkHttpStatusCodeErrorDetectionStrategy(),
3,
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(20),
TimeSpan.FromSeconds(1));
var middleware = options.Middleware;
middleware.Add(new ConversationState<ChatLog>(new MemoryStorage()));
middleware.Add(new MyCustomMiddleware()); // <- I want to inject a typed HttpClient here
//... etc. ....
是否有不同的方式来配置允许依赖注入的机器人?
如果MyCustomMiddleware 在其构造函数中需要一个类型化的HttpClient,我必须在此处创建一个新实例,因此我无法从 DI 和我刚刚设置的配置中受益。
【问题讨论】:
标签: c# asp.net-core .net-core asp.net-core-2.1 azure-bot-service