我有一个组件在Castle Windsor注册,它依赖于组件列表,每个组件都由一个接口表示。 Castle Windsor的配置与下面的代码类似。如何在创建组件的过程中配置Castle Windsor错误处理?
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
//Allow the container to resolve all IFooComponent
//as IEnumerable<IFooComponent>
container.Kernel.Resolver
.AddSubResolver(new CollectionResolver(container.Kernel, false));
container.Register(
Component
.For<IMainService>()
.ImplementedBy<AwesomeMainService>());
container.Register(
Component.For<IFooComponent>()
.ImplementedBy<CoolFooComponent>()
.Named(typeof (CoolFooComponent).Name),
Component.For<IFooComponent>()
.ImplementedBy<FooComponentWithUnresolvedDependancy>()
.Named(typeof (FooComponentWithUnresolvedDependancy).Name)
//....
);
}
}
AwesomeMainService
依赖于IEnumerable<IFooComponent>
像下面
public class AwesomeMainService : IMainService
{
public AwesomeMainService(IEnumerable<IFooComponent> fooComponents)
{
//I could count the fooComponents here but this is a hack
}
}
现在,如果IFooComponent
S的一个缺失的依赖,或温莎城堡否则遇到在实例化一个IFooComponent
异常,异常被捕获温莎城堡并没有重新出现。当我解决注册的IMainService
实例时,一切都显示正常,因为至少可以创建IFooComponent
的实例。
//No exception here because there is at least 1 IFooComponent
var plugin = _container.Resolve<IMainService>();
如何处理此错误并关闭所有内容?我本以为会有一个event on the Kernel,但似乎没有。
我修复:
我创建AwesomeMainService
其中计数的注册IFooProcessor
S上的数目的动态参数。然后AwesomeMainService
验证了这与提供的IFooProcessor
s的数量匹配。
public class AwesomeMainService : IMainService
{
public AwesomeMainService(IEnumerable<IFooComponent> fooComponents,
int expectedProcessorCount)
{
Verify.That(fooComponents.Count == expectedProcessorCount,
"requestProcessors does not match the expected number " +
"of processors provided");
}
}
然后,我已将此添加到AwesomeMainService登记:
.DynamicParameters((kernel, parameters) =>
{
parameters["expectedProcessorCount"] =
container.Kernel.GetAssignableHandlers(typeof (object))
.Where(
h => h.ComponentModel.Service.UnderlyingSystemType ==
typeof (IRequestProcessor))
.Count();
}));
太棒了!我希望你能找到我的问题。不幸的是,我不确定我可以跳到这个项目的测试版。在此期间,作为一种解决方法,是否有一些方法可以计算在Container或Kernel中配置的IFooComponent的数量,以便将此值作为DynamicParameter提供给AwesomeMainService的ctor?这是我需要做什么来获得组件? http://stackoverflow.com/questions/2951989/list-all-iregistrations-in-windsorcontainer-kernel – drstevens
计数'IFooComponent's cont:我想我也可以使用'ComponentRegistered'事件来计数这些。有没有更好的办法? – drstevens
是的,其中一个事件(可能是'ComponentModelCreated')是一个很好的连接的地方,然后有一个测试,根据集合解析组件,确保它获得所需的所有依赖。 –