问题
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