In Autofac how do I change the instance that is re

2020-05-19 21:46发布

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.

3条回答
你好瞎i
2楼-- · 2020-05-19 22:18

At the time you want to change the registration, create a new ContainerBuilder, register the new instance, and call Update passing in the container:

// at some later point...
builder = new ContainerBuilder();
builder.RegisterInstance(myType2);
builder.Update(container);
查看更多
3楼-- · 2020-05-19 22:27

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

builder.Register<TInterface>(c => c.Resolve<TConcrete>())
       .OnActivating(e => e.ReplaceInstance(new TInterfaceSubclass()));

https://autofaccn.readthedocs.io/en/latest/lifetime/events.html#onactivating

查看更多
啃猪蹄的小仙女
4楼-- · 2020-05-19 22:40

An alternative could be to register a delegate that is able to change the underlying instance provided by the container. Consider the following code:

 var theInstance = new MyType();
 var builder = new ContainerBuilder();
 builder.Register(context => theInstance);
 builder.Register<Action<MyType>>(context => newInstance => theInstance = newInstance);
 var container = builder.Build();

You can now resolve the action to get a delegate that can change the registration:

 var updateInstance = c.Resolve<Action<MyType>>();
 updateInstance(new MyType());

Note: if you could elaborate on when and why you need to change the instance, perhaps we could even find a better solution.

查看更多
登录 后发表回答