在构建容器之后添加服务

是否有可能在运行时注册一个服务,也就是在构建了 ContainerBuilder并创建了 Container(处理了 ContainerBuilder)之后?

20155 次浏览

Yes you can, using the Update method on ContainerBuilder:

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


newBuilder.Update(existingContainer);

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