gpt4 book ai didi

c# - Bot Framework Autofac DI - 使用 context.Call() 时传递依赖项

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

我一直在研究机器人框架,但我只是想知道在使用 context.Call() 时我对 Autofac 的使用是否正确。我应该像这样(如下)将评级服务依赖项从 RootDialog 传递到 ReviewDialog,还是有更好的方法?

context.Call(new ReviewDialog(_ratingService), ChildDialogHasCompleted);

消息 Controller

    [BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
{
await Conversation.SendAsync(activity, () => scope.Resolve<IDialog<object>>());
}
}

var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
}

根对话框

[Serializable]
public class RootDialog : LuisDialog<object>
{
private IRatingService _ratingService;

public RootDialog(IRatingService ratingService)
{
this._ratingService = ratingService;
}

[LuisIntent("Movie")]
public async Task IntentSearch(IDialogContext context, LuisResult result)
{
// Do stuff

context.Call(new ReviewDialog(_ratingService), ChildDialogHasCompleted);
}

private async Task ChildDialogHasCompleted(IDialogContext context, IAwaitable<object> msg)
{
context.Done(true);
}
}

评论对话框

[Serializable]
public class ReviewDialog : IDialog
{
private IRatingService _ratingService;

public ReviewDialog(IRatingService ratingService)
{
this._ratingService = ratingService;
}

public async Task StartAsync(IDialogContext context)
{
PromptDialog.Choice(context, ProcessRating, new List<string> { "1", "2", "3", "4", "5" }, "Please select your rating");
}

public async Task ProcessRating(IDialogContext context, IAwaitable<string> msg)
{
var message = await msg;

context.UserData.TryGetValue("SelectedMovieId", out int movieId);

var rating = int.Parse(message);

_ratingService.Save(movieId, rating);

await context.PostAsync("Thank you");

context.Done(true);
}
}

全局

public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);

var builder = new ContainerBuilder();

builder.RegisterType<RootDialog>()
.As<IDialog<object>>()
.InstancePerDependency();

builder.RegisterType<RatingService>()
.Keyed<IRatingService>(FiberModule.Key_DoNotSerialize)
.AsImplementedInterfaces();

builder.Update(Conversation.Container);
}
}

如有任何帮助,我们将不胜感激。

最佳答案

您这样做的方式完全有效。要查看另一个实现,请查看 AlarmBot

你这样做的方式通常也是我在对话框中使用 DI 的方式。还有另一种方法可以使用上下文 PrivateConversationDataConversationDataUserData 中的数据包在对话框之间传递数据/类,但没有错用你做事的方式

关于c# - Bot Framework Autofac DI - 使用 context.Call() 时传递依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871537/

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