简体   繁体   中英

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.

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(...)
}

您需要使用IHandlerSelector

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM