5

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.

Richard Garside
  • 87,839
  • 11
  • 80
  • 93
Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42
  • Possible duplicate: http://stackoverflow.com/questions/9253388/in-castle-windsor-3-override-an-existing-component-registration-in-a-unit-test – Andrew Shepherd Feb 06 '17 at 00:34

3 Answers3

5

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(...)
}
stuartd
  • 70,509
  • 14
  • 132
  • 163
  • This one was useful, also added "managedExternally: true" parameter to UsingFactoryMethod() to return singleton object which I reinstantiate whenever I want. A bit dirty solution though :) – Mert Akcakaya Sep 17 '13 at 11:52
2

See this answer: https://stackoverflow.com/a/16832183/4593944

Register the new component with IsDefault and it becomes the preferred resolver.

If you already have a container with instances that you want to reset, usually singletons, just call Dispose on container.

Community
  • 1
  • 1
Daniel Reis
  • 850
  • 9
  • 10
1

You need to use an IHandlerSelector.

Crixo
  • 3,060
  • 1
  • 24
  • 32
  • This example talks about switching from one implementation to another. In my code, I am using the same implementation, Foo, but want it to be reinstantiated with different parameters. – Mert Akcakaya Sep 17 '13 at 10:59
  • Ok. Understood. You may consider also a TypedFactory w/ a custom ITypedFactoryComponentSelector.http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx?HL=typedfactory – Crixo Sep 17 '13 at 12:14