是否可以在创建 Autofac LifetimeScope 后向其添加注册?

Is it possible to add registrations to an Autofac LifetimeScope after it was created?

我知道您可以将注册添加到 LifetimeScope 它是这样创建的:

using(var scope = container.BeginLifetimeScope(builder =>  
    {  builder.RegisterType<Override>().As<IService>();
       builder.RegisterModule<MyModule>();
    }))
{
  // The additional registrations will be available
  // only in this lifetime scope.
}

是否可以在 创建 之后添加注册 LifetimeScope? (例如在 using 块中添加注册)

您可以访问 ILifetimeScopeComponentRegistry 属性,使用此对象您可以注册新的 IComponentRegistration,您可以使用 RegistrationBuilder static 创建它方法:

using(var scope = container.BeginLifetimeScope())
{
    var registration = RegistrationBuilder.ForType<ServiceA>()
                                          .As<IService>()
                                          .CreateRegistration();
    scope.ComponentRegistry.Register(registration); 

    scope.Resolve<IService>(); 
}