在 Autofac 中,如何更改调用 Build 后注册的实例?
假设我有这段代码
var builder = new ContainerBuilder();
builder.RegisterInstance(new MyType());
var container = builder.Build();
,然后一段时间后,我想为 container
上调用的所有未来解析更改 MyType
的实例。
So lets say i have this code
var builder = new ContainerBuilder();
builder.RegisterInstance(new MyType());
var container = builder.Build();
Then some time later I want to change the instance of MyType
for all future resolves that are called on container
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您想要更改注册时,创建一个新的 ContainerBuilder,注册新实例,并调用传入容器的
Update
:At the time you want to change the registration, create a new
ContainerBuilder
, register the new instance, and callUpdate
passing in the container:另一种方法是注册一个能够更改容器提供的底层实例的委托。考虑以下代码:
您现在可以解析操作以获取可以更改注册的委托:
注意:如果您可以详细说明何时和为什么 您需要更改实例,也许我们甚至可以找到更好的解决方案。
An alternative could be to register a delegate that is able to change the underlying instance provided by the container. Consider the following code:
You can now resolve the action to get a delegate that can change the registration:
Note: if you could elaborate on when and why you need to change the instance, perhaps we could even find a better solution.
您还可以利用 Autofac Lifetime 事件“OnActivating”,并在内存中拥有自己的控制器对象,该对象会替换已解析的实例,如下所示
https://autofaccn.readthedocs.io/en/latest/lifetime/events.html#onactivating
You can also make use of the Autofac Lifetime event "OnActivating" and have your own controller object in memory which replaces the resolved instance like so
https://autofaccn.readthedocs.io/en/latest/lifetime/events.html#onactivating