Adding services after container has been built

不羁岁月 提交于 2019-11-28 16:55:08

问题


Is it possible to register a service at run-time, meaning after the ContainerBuilder has been built and the Container has been created (and ContainerBuilder disposed of)?


回答1:


Yes you can, using the Update method on ContainerBuilder:

var newBuilder = new ContainerBuilder();
newBuilder.Register...;

newBuilder.Update(existingContainer);



回答2:


Since ContainerBuilder.Update has been deprecated, the new recommendation is to use child lifetime scope.

Adding Registrations to a Lifetime Scope

Autofac allows you to add registrations “on the fly” as you create lifetime scopes. This can help you when you need to do a sort of “spot weld” limited registration override or if you generally just need some additional stuff in a scope that you don’t want to register globally. You do this by passing a lambda to BeginLifetimeScope() that takes a ContainerBuilder and adds registrations.

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.
}

Working with Lifetime Scopes



来源:https://stackoverflow.com/questions/4998870/adding-services-after-container-has-been-built

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!