2011-11-18 61 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')是一個很好的連接的地方,然後有一個測試,根據集合解析組件,確保它獲得所需的所有依賴。 –

相關問題