簡體   English   中英

Castle Windsor - 刪除或更改已注冊的實例

[英]Castle Windsor - Removing or changing a registered instance

我想用在運行時創建的另一個實例更改已注冊的實例。

這可以是刪除現有組件並重新注冊新組件,或者只是將新創建的實例重新分配給已注冊的組件。

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));

有沒有辦法做到這一點? 請不要提出其他想法,例如“重新初始化您的IoC容器”等。

如果你不得不多次這樣做,你可以考慮使用UsingFactoryMethodLifestyle.Transient注冊IFoo ,所以每次你得到一個實例時它會使用最新的參數:

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

...


private IFoo GetLatestFoo()
{
    return new Foo(...)
}

您需要使用IHandlerSelector

請參閱此答案: https//stackoverflow.com/a/16832183/4593944

使用IsDefault注冊新組件,它將成為首選的解析程序。

如果您已經有一個容器,其中包含要重置的實例,通常是單例,只需在容器上調用Dispose即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM