[英]Azure Function, Dependency Injection and loop
I have the following code:我有以下代码:
Startup.cs:启动.cs:
services.AddTransient<ProcessPendingDeactivateDeviceStatus>();
Function code: Function 代码:
public class FunctionPendingDeactivationStatusesCheck
{
private readonly IDeviceService _deviceService;
private readonly ProcessPendingDeactivateDeviceStatus _pendingDeviceStatus;
public FunctionPendingDeactivationStatusesCheck(
IDeviceService deviceService,
ProcessPendingDeactivateDeviceStatus pendingDeviceStatus)
{
_deviceService = deviceService;
_pendingDeviceStatus = pendingDeviceStatus;
}
[Singleton]
[FunctionName("FunctionPendingDeactivationStatusesCheck")]
public async Task Run([TimerTrigger("0 12,27,42,57 * * * *")] TimerInfo myTimer, ExecutionContext context, ILogger log)
{
var pendingDeletingDevices = _deviceService.GetDevicesByStatus(DeviceStatus.PendingDeleted);
foreach (var device in pendingDeletingDevices)
{
await _pendingDeviceStatus.InitAsync(device);
so, as we can see, we call InitAsync
inside loop and work with the same instance for all iterations.因此,正如我们所见,我们在循环内调用
InitAsync
并在所有迭代中使用相同的实例。 I want to recreate this object for every iteration.我想为每次迭代重新创建这个 object 。 How to do it?
怎么做?
A factory will be needed to get the desired behavior.需要工厂才能获得所需的行为。
Register a factory delegate that will be used to create the instances注册将用于创建实例的工厂委托
services.AddTransient<ProcessPendingDeactivateDeviceStatus>();
services.AddSingleton<Func<ProcessPendingDeactivateDeviceStatus>>(sp =>
() => sp.GetRequiredService<ProcessPendingDeactivateDeviceStatus>()
);
Inject the factory and create instance as needed注入工厂并根据需要创建实例
public class FunctionPendingDeactivationStatusesCheck {
private readonly IDeviceService _deviceService;
private readonly Func<ProcessPendingDeactivateDeviceStatus> factory;
public FunctionPendingDeactivationStatusesCheck(
IDeviceService deviceService,
Func<ProcessPendingDeactivateDeviceStatus> factory) {
_deviceService = deviceService;
this.factory = factory;
}
[Singleton]
[FunctionName("FunctionPendingDeactivationStatusesCheck")]
public async Task Run([TimerTrigger("0 12,27,42,57 * * * *")] TimerInfo myTimer, ExecutionContext context, ILogger log) {
var pendingDeletingDevices = _deviceService.GetDevicesByStatus(DeviceStatus.PendingDeleted);
foreach (var device in pendingDeletingDevices) {
ProcessPendingDeactivateDeviceStatus _pendingDeviceStatus = factory();
await _pendingDeviceStatus.InitAsync(device);
//...
Every time factory
is invoked, a new transient instance will be created by the container.每次调用
factory
时,容器都会创建一个新的瞬态实例。
Without any details as to why a new instance is needed for each iteration, there is no way to tell if there will be any adverse effects of creating that many instances in cases where there are many devices.如果没有关于为什么每次迭代都需要一个新实例的任何细节,就无法判断在有很多设备的情况下创建那么多实例是否会产生任何不利影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.