2009-06-07 98 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