温莎城堡:我怎样才能更新组件注册
-
06-09-2019 - |
题
如果我在配置已经定义:
container.Register(
Component.For<X.Y.Z.IActivityService>()
.ImplementedBy<X.Y.Z.ActivityService>()
.ServiceOverrides(ServiceOverride.ForKey("Listeners").Eq(new [] { typeof(X.Y.Z.DefaultActivityListener).FullName }))
.LifeStyle.Transient
);
和我希望延长此配置,并加入到听众数组属性的新项目,使得最终的配置是有效的:
container.Register(
Component.For<X.Y.Z.IActivityService>()
.ImplementedBy<X.Y.Z.ActivityService>()
.ServiceOverrides(ServiceOverride.ForKey("Listeners").Eq(new [] { typeof(X.Y.Z.DefaultActivityListener).FullName, "MyOtherListenerID" }))
.LifeStyle.Transient
);
我必须知道“阵列”的内容时第一登记部件,或我可以检索组件注册和添加到它?
我希望使用装饰图案,使得我可以建立我的容器,然后根据需要为不同的场景扩展它来实现我的配置。这意味着我需要能够访问已配置的组件和添加至它们。
正想着具有类DefaultConfig
其返回默认设置和然后的更“DecoratedConfig
”类之一,这将延长默认的配置。
因此,我将有
IWindsorContaner c = new DecoratedConfig(new DefaultConfig()).InitialiseContainer();
DefaultConfig
应设置一个ActivityService
与DefaultActivityListener
(如实施例中示出)。
DecoratedConfig
会认识到,ActivityService
已经建立,并添加了自己的监听器实现对Listeners
的ActivityService
阵列。
感谢。
解决方案
订阅Kernel.ComponentModelCreated
事件。您可以从那里更改任何元件参数。请参见这个。它没有的的的是一个工厂谁这样做,但它的方便。
其他提示
@mausch,adusting的ComponentModel
配置似乎是该溶液中。
在以下测试effecitvely做什么,我需要,而无需在钩到ComponentModelCreatedEvent
所以我可以进行更改创建组件模型甚至之后。
我将包装的功能扩展方法,和尝试,并装配到一个流利API。
[TestMethod]
public void ArrayPropertyTestApi3()
{
using (Castle.Windsor.WindsorContainer container = new Castle.Windsor.WindsorContainer())
{
container.Register(Component.For<Components.A>().ServiceOverrides(ServiceOverride.ForKey("I").Eq(new[] { typeof(Components.B).FullName })));
container.Register(Component.For<Components.B>());
container.Register(Component.For<Components.C>());
IHandler h = container.Kernel.GetHandler(typeof(Components.A));
if (h != null)
{
var config = h.ComponentModel.Configuration;
if (config != null)
{
var items = config.Children.Single(c => c.Name == "parameters")
.Children.Single(c => c.Name == "I")
.Children.Single(c => c.Name == "list")
as MutableConfiguration;
items.Children.Add(new MutableConfiguration("item", string.Format("${{{0}}}", typeof(Components.C).FullName)));
}
}
Components.A svc = container.Resolve<Components.A>();
Assert.IsTrue(svc.I.Length == 2);
Assert.IsTrue(svc.I[0].Name == "B");
Assert.IsTrue(svc.I[1].Name == "C");
}
}
有优选使用href="http://docs.castleproject.org/Windsor.ComponentModel-construction-contributors.ashx" rel="nofollow"> ComponentModel施工贡献者与 要做到这一点,你会实现接口来指定更改应用于配置。 然后注册您的组件之前,您只需将该类添加到您的容器: 所有的部件将接着穿过这个类,在这里可以改变它们的结构。你的情况量变到质变的听众列表,等等(我想这是拦截器的以前的名称)IContributeComponentModelConstruction
的所述
public class ChangeConfiguration : IContributeComponentModelConstruction
{
public void ProcessModel(IKernel kernel, ComponentModel model)
{
// filter your model to match the subset you're interested in
// change the configuration for matching models
}
}
container.Kernel.ComponentModelBuilder.AddContributor(new ChangeConfiguration());