views:

22

answers:

2

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.

+1  A: 

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);
adrift
A: 

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.

Peter Lillevold