2009-06-07 127 views
0

我在我自己的實現的解析器模式中使用溫莎城堡。我有一個服務MethodAServiceMethodBService的兩個實現,它們都實現了IMethodService。我在使用Windsor時使用「Convention Over Configuration」。我如何告訴Castle Windsor在一個實例中使用MethodAService(調試,發佈等),但在另一個實例中,請使用MethodBService。感謝您的時間!基於構建或配置文件的城堡溫莎配置

+0

問題補充到溫莎FAQ:http://using.castleproject.org/display/IoC/FAQ – 2010-01-24 17:02:35

回答

2

這裏有一個辦法做到這一點,利用IHandlerSelector

public class DebugHandlerSelector: IHandlerSelector { 
    private readonly Type serviceType; 
    private readonly Type debugImplementation; 
    private readonly Type releaseImplementation; 

    public DebugHandlerSelector(Type serviceType, Type debugImplementation, Type releaseImplementation) { 
     this.serviceType = serviceType; 
     this.debugImplementation = debugImplementation; 
     this.releaseImplementation = releaseImplementation; 
    } 

    public bool HasOpinionAbout(string key, Type service) { 
     return service == serviceType; 
    } 

    public IHandler SelectHandler(string key, Type service, IHandler[] handlers) { 
     return handlers.First(h => h.ComponentModel.Implementation == 
#if DEBUG 
      debugImplementation 
#else 
      releaseImplementation 
#endif      
      ); 
    } 
} 

使用範例:

container.Kernel.AddHandlerSelector(new DebugHandlerSelector(typeof(IMethodService), typeof(MethodAService), typeof(MethodBService))); 
+1

如何使這不依賴於IHandlerSelector? – 2009-06-07 21:43:32