97

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)?

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
Paul Knopf
  • 9,568
  • 23
  • 77
  • 142
  • Currently, best practices say AutoFac containers [are immutable](https://autofaccn.readthedocs.io/en/latest/best-practices/index.html#consider-a-container-as-immutable) – Ady Sep 21 '19 at 14:58

2 Answers2

98

Yes you can, using the Update method on ContainerBuilder:

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

newBuilder.Update(existingContainer);
huysentruitw
  • 27,376
  • 9
  • 90
  • 133
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • 2
    Do note that updating an existing container that has already been used to resolve can result in undeterministic behavior. For instance, replacing components that are dependencies of already resolved singletons cause the original component to stay referenced. – Steven May 18 '16 at 08:33
  • 18
    Update is being deprecated https://github.com/autofac/Autofac/issues/811. – Chase Florell Mar 27 '17 at 23:44
  • 1
    Yes, it is obsolete, and I came here to find the alternate option – Mohammed Dawood Ansari Oct 06 '21 at 12:02
30

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

Niels R.
  • 7,260
  • 5
  • 32
  • 44
wezzix
  • 1,984
  • 1
  • 19
  • 18
  • 1
    The thing to note is that comment in the using block. "The additional registrations will be available only in this lifetime scope." – Ady Sep 21 '19 at 14:57