gpt4 book ai didi

c# - 在 IDialog 中使用 ILifetimeScope

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:52 25 4
gpt4 key购买 nike

我正在使用 Microsoft Bot Framework 创建机器人。我正在将 POST 上的对话框调用到 MessageController,如下所示:

using (var scope = DialogModule.BeginLifetimeScope(_scope, activity))
{
var postToBot = scope.Resolve<IPostToBot>();
await postToBot.PostAsync(activity, cancellationToken);
}

在我的 Dialog 类中,我需要使用一个使用此范围的工厂。问题是在 Dialog 类中获取此范围。

如果我在构造函数上注入(inject) ILifetimeScope,它会第一次起作用。但这种类型不可序列化(在 BotFramework 上引发错误)。所以我必须将其标记为不可序列化,但我无法再次获得此范围。我尝试使用默认的 WebApi DependencyResolver,但我需要一个 AutoFac 功能来解析键控服务。如果我从 DependencyResolver 解析 ILifetimeScope,那么它返回“根”范围,我需要嵌套范围(与消息 Controller 上使用的相同)。

我解决了将范围保持在静态变量中的问题,但这并不优雅。

using (var scope = DialogModule.BeginLifetimeScope(_scope, activity))
{
IocModule.CurrentScope = scope;

var postToBot = scope.Resolve<IPostToBot>();
await postToBot.PostAsync(activity, cancellationToken);
}

还有其他想法吗?

最佳答案

您应该能够注入(inject) IComponentContext,这将帮助您解决依赖关系。

查看 DialogFactory来自 ContosoFlowers 的类(class)样本。也看看 ContosoFlowersDialogFactory实现 DialogFactory 的类。在ContosoFlowersModule class 你会看到那个工厂的注册信息。

builder.RegisterType<ContosoFlowersDialogFactory>()
.Keyed<IContosoFlowersDialogFactory>(FiberModule.Key_DoNotSerialize)
.AsImplementedInterfaces()
.InstancePerLifetimeScope();

构造函数需要 IComponentContext

public ContosoFlowersDialogFactory(IComponentContext scope)

关于在您的对话框中引用不可序列化服务,将它们标记为不可序列化并不是唯一的方法。您还可以使用 FiberModule.Key_DoNotSerialize解决依赖关系。您可以在此 Technical FAQ section 中阅读更多有关引用不可序列化服务的不同方法的信息。 .

关于c# - 在 IDialog 中使用 ILifetimeScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39841983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com