【发布时间】:2019-06-03 16:09:07
【问题描述】:
我正在编写一个在呼叫中心使用的应用程序。每当电话打到工作站时,我都需要创建一组对象(可能大约 30 个)。我希望这些对象仅在通话期间存在,因为它们包含状态,并且我认为创建新对象比尝试在每次通话时重置它们的状态更有意义。在创建这些对象时,它必须执行一些异步活动,例如为其他应用程序建立多个套接字并向它们发送消息。当电话结束时,它必须做更多的异步操作,例如发送结束通话消息,然后关闭套接字。
我一直在研究 Simple Injector 的 AsyncScopedLifestyle 功能。这是我认为如何使用它的简化示例:
class CallTaskFactory
{
private readonly Container Container;
public CallTaskFactory(Container container)
{
Container = container;
}
public async Task CreateCallTask()
{
using (Scope scope = AsyncScopedLifestyle.BeginScope(Container))
{
// Get the socket's destination
SocketDestinationProvider socketDestProvider =
Container.GetInstance<SocketDestinationProvider>();
EndPoint ep = await socketDestProvider.GetSocketDestination();
// Now create a socket and connect to that destination
Socket socket = Container.GetInstance<Socket>();
await socket.ConnectAsync(ep);
// Send a simple message on the socket
var Sender1 = Container.GetInstance<MessageSender1>();
await Sender1.SendStartMessage();
// Send another message, and the response tells us whether we need
// to create some object that does something on a timer
var Sender2 = Container.GetInstance<MessageSender2>();
var Response = await Sender2.SendStartMessageAndAwaitResponse();
if (Response.Result)
{
Container.GetInstance<ClassThatChecksSomethingOnATimer>();
}
// The call stays active until the socket closes
TaskCompletionSource<int> Completion = new TaskCompletionSource<int>();
socket.Closed += (sender, e) => { Completion.TrySetResult(0); };
await Completion.Task;
// Clean up
await Sender2.SendStopMessage();
await Sender1.SendStopMessage();
await socket.DisconnectAsync();
}
}
}
不过,我不确定我是否将其放置在正确的位置。我假设这个工厂类必须存在于我的 Composition Root 中,因为它引用了一个特定的 DI 容器。但对我而言,Composition Root 仅用于组合对象图,并且通常它没有使用这些对象的逻辑,就像上面的代码那样。
如何在一个地方创建一组对象并在另一个地方使用它们,然后在它们的工作完成时销毁它们?
【问题讨论】:
标签: c# dependency-injection async-await ioc-container simple-injector