在Autofac中,如何更改在调用Build之后注册的实例?

Sim*_*mon 30 .net dependency-injection ioc-container autofac

所以我要说我有这个代码

var builder = new ContainerBuilder();
builder.RegisterInstance(new MyType());
var container = builder.Build();
Run Code Online (Sandbox Code Playgroud)

然后一段时间后,我想更改MyType所有未来调用的实例container.

Jef*_*ata 47

在您想要更改注册时,创建一个新的ContainerBuilder,注册新实例,并Update在容器中调用传递:

// at some later point...
builder = new ContainerBuilder();
builder.RegisterInstance(myType2);
builder.Update(container);
Run Code Online (Sandbox Code Playgroud)

  • 更新(容器)已废弃.建议重建容器. (3认同)

Pet*_*old 20

另一种方法是注册能够更改容器提供的基础实例的委托.请考虑以下代码:

 var theInstance = new MyType();
 var builder = new ContainerBuilder();
 builder.Register(context => theInstance);
 builder.Register<Action<MyType>>(context => newInstance => theInstance = newInstance);
 var container = builder.Build();
Run Code Online (Sandbox Code Playgroud)

您现在可以解决该操作以获取可以更改注册的委托:

 var updateInstance = c.Resolve<Action<MyType>>();
 updateInstance(new MyType());
Run Code Online (Sandbox Code Playgroud)

注意:如果您可以详细说明何时以及为何需要更改实例,我们甚至可以找到更好的解决方案.