Castle Windsor配置基于构建或配置文件

时间:2009-06-07 19:11:05

标签: c# configuration dependency-injection castle-windsor

我在自己的Resolver Pattern实现中使用Castle Windsor。我有两个服务MethodAServiceMethodBService的实现,它们都实现了IMethodService。我在引导Windsor时使用“Convention Over Configuration”。如何告诉Castle Windsor在一个实例中使用MethodAService(Debug,Release等),但在另一个实例中,使用{{1} }。谢谢你的时间!

1 个答案:

答案 0 :(得分: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)));