我只是想知道DI期间是否可以有
async/await
。
执行以下操作,DI 无法解决我的服务。
services.AddScoped(async provider =>
{
var client = new MyClient();
await client.ConnectAsync();
return client;
});
以下内容完全正常。
services.AddScoped(provider =>
{
var client = new MyClient();
client.ConnectAsync().Wait();
return client;
});
虽然理论上可以在对象解析期间使用 async/await,但您应该考虑以下限制:
由于这些限制,最好将涉及 I/O 的所有事情推迟到对象图构建完成之后。
因此,
MyClient
不应注入已连接的MyClient
,而应该在第一次使用时连接,而不是在创建时连接。
由于您的
MyClient
不是应用程序组件而是第三方组件,这意味着您无法确保它“在第一次使用时连接。”
但这不应该是一个问题,因为依赖倒置原则已经告诉我们:
摘要归上层/政策层所有
这意味着应用程序组件不应直接依赖于第三方组件,而应依赖于应用程序本身定义的抽象。作为Composition Root的一部分,可以编写适配器来实现这些抽象并使应用程序代码适应第三方库。
这样做的一个重要优点是,您可以控制应用程序组件使用的 API,这是成功的关键,因为它允许将连接问题完全隐藏在抽象背后。
以下是应用程序定制抽象的示例:
public interface IMyAppService
{
Task<Data> GetData();
Task SendData(Data data);
}
请注意,这个抽象缺少
ConnectAsync
方法;这隐藏在抽象的背后。例如,看看以下适配器:
public sealed class MyClientAdapter : IMyAppService, IDisposable
{
private readonly Lazy<Task<MyClient>> connectedClient;
public MyClientAdapter()
{
this.connectedClient = new Lazy<Task<MyClient>>(async () =>
{
var client = new MyClient();
await client.ConnectAsync();
return client;
});
}
public async Task<Data> GetData()
{
var client = await this.connectedClient.Value;
return await client.GetData();
}
public async Task SendData(Data data)
{
var client = await this.connectedClient.Value;
await client.SendData(data);
}
public void Dispose()
{
if (this.connectedClient.IsValueCreated)
this.connectedClient.Value.Dispose();
}
}
适配器对应用程序代码隐藏连接详细信息。它将
MyClient
的创建和连接包装在 Lazy<T>
中,这允许客户端仅连接一次,而与调用 GetData
和 SendData
方法的顺序以及调用次数无关。
这允许您让应用程序组件依赖于
IMyAppService
而不是 MyClient
,并使用适当的生活方式将 MyClientAdapter
注册为 IMyAppService
。