2011-11-18 75 views
2

我有一个组件在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验证了这与提供的IFooProcessors的数量匹配。

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

回答

3

这是温莎2.5和更早的已知限制。该方案将快速失败的温莎3

在v3中也有一个新的事件EmptyCollectionResolving当组件取决于IFoo秒的集合,但对于IFoo没有组件在容器中注册该上升。

+0

太棒了!我希望你能找到我的问题。不幸的是,我不确定我可以跳到这个项目的测试版。在此期间,作为一种解决方法,是否有一些方法可以计算在Container或Kernel中配置的IFooComponent的数量,以便将此值作为DynamicParameter提供给AwesomeMainService的ctor?这是我需要做什么来获得组件? http://stackoverflow.com/questions/2951989/list-all-iregistrations-in-windsorcontainer-kernel – drstevens

+0

计数'IFooComponent's cont:我想我也可以使用'ComponentRegistered'事件来计数这些。有没有更好的办法? – drstevens

+0

是的,其中一个事件(可能是'ComponentModelCreated')是一个很好的连接的地方,然后有一个测试,根据集合解析组件,确保它获得所需的所有依赖。 –

相关问题