Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Castle Windsor - Removing or changing a registered instance

I want to change the registered instance with another instance created at runtime.

This can be removing existing component and re-registering the new one, or just reassigning the newly created instance to the registered one.

Foo old = new Foo("asd");
IoC.Register(Component.For<IFoo>().Instance(old));

Foo new = new Foo("qwe");
IoC.Unregister(old); // RemoveComponent method is removed from IKernel after v3.0
IoC.Register(Component.For<IFoo>().Instance(new));

Is there a way to do that? Please do not suggest other ideas such as "re-intialize your IoC container" etc.

like image 658
Mert Akcakaya Avatar asked Feb 15 '23 06:02

Mert Akcakaya


1 Answers

If you have to do this more than once, you could consider registering IFoo with UsingFactoryMethod and Lifestyle.Transient, so each time you get an instance it uses the latest parameters:

Component.For<IFoo>().UsingFactoryMethod(GetLatestFoo).Lifestyle.Transient

...


private IFoo GetLatestFoo()
{
    return new Foo(...)
}
like image 174
stuartd Avatar answered Feb 17 '23 21:02

stuartd