在 azure 函数中手动调用 CreateScope() 或 BeginScope()

Calling CreateScope() or BeginScope() Manually inside azure function

我正在编写一个 eventhub 触发的 azure 函数,它从 eventhub 接收每个事件中的对象列表。我想为我收到的列表中的每个对象实例化某种类型的对象。如果我通过调用 builder.Services.AddScoped 将该类型注册为作用域,我将为每个 eventhub 事件(每个函数调用)创建一个新实例。我想控制实例创建。所以我想在我的函数中加入类似下面的东西。

 using (var scope = builder.Services.BuildServiceProvider().CreateScope())
            {
               // scope.ServiceProvider.GetService(type)
            }

通过这种方式,对于每个事件中心事件中列表中的每个对象,我都可以拥有某种类型的新实例。

我找到了问题的解决方案。在 Startup 的 Configure 方法中,我们可以像下面这样注册 ServiceProvider

builder.Services.AddScoped<IEventContext, EventContext>();
builder.Services.AddSingleton<ServiceProvider>(builder.Services.BuildServiceProvider());

然后我们可以在函数app class中设置ServiceProvider作为依赖,我们可以像下面这样在function

中直接调用CreateScope()
 using (var scope = this._serviceProvider.CreateScope())
      {
          var ctx = scope.ServiceProvider.GetService<IEventContext>();

          var ctx2 = scope.ServiceProvider.GetService<IEventContext>();

          this._logger.LogInformation(ctx.GetHashCode().ToString());  //same
          this._logger.LogInformation(ctx2.GetHashCode().ToString());  //same
               
       }