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.
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(...)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With