Windsor Ioc Service Overrides:已经为给定密钥注册了一个组件

时间:2011-10-22 09:46:59

标签: c# inversion-of-control castle-windsor ioc-container

我一直在尝试配置Windsor,为服务提供不同的实现,具体取决于正在构建的类:

我读过这个 http://docs.castleproject.org/Windsor.Registering-components-one-by-one.ashx#Supplying_the_component_for_a_dependency_to_use_Service_override_9

昨天问了这个问题 Windsor Ioc container: How to register that certain constructors take different implementation of an interface

当我直接解析该类时,该问题的答案正常工作,但是当它在一个深层次的对象图中时却没有,并且我想要覆盖的类被用作另一个接口的默认实现注册

e.g。

我有2个MVC控制器。一个用于记录,一个用于cardpayments。日志记录提供程序采用日志记录提供程序,后者又接受IService。 CardPayment控制器需要一个卡支付提供商,而后者又需要一个IService。 cardpayment提供商应获得安全服务,日志服务提供商应获得正常服务

代码如下:

注册记忆:

Component.For<ILoggingProvider>().ImplementedBy<LoggingProvider>(),
Component.For<ICardPaymentProvider>().ImplementedBy<CardPaymentProvider>(),
Component.For<IService>().ImplementedBy<WebService>().Named("default"),
Component.For<IService>().ImplementedBy<SecureWebService>().Named("secure"),
Component.For<CardPaymentProvider>().ServiceOverrides(ServiceOverride.ForKey("service").Eq("secure")),
Component.For<LoggingProvider>().ServiceOverrides(ServiceOverride.ForKey("service").Eq("default"))

类层次结构:

 public LoggingController(ILoggingProvider loggingProvider)
 {
            this.loggingProvider = loggingProvider;
 }

 public CardPaymentController(ICardPaymentProvider cardPaymentProvider)
{
            this.cardPaymentProvider = cardPaymentProvider;
}

    public interface IService
    {
        void Doit();
    }
    public class WebService : IService
    {
        public void Doit()
        {
            throw new NotImplementedException();
        }
    }
    public class SecureWebService : IService
    {
        public void Doit()
        {
            throw new NotImplementedException();
        }
    }
    public class CardPaymentProvider : ICardPaymentProvider
    {
        private readonly IService service;
        public CardPaymentProvider(IService service)
        {
            this.service = service;
        }
    }
    public interface ICardPaymentProvider
    {
    }
    public class LoggingProvider : ILoggingProvider
    {
        private readonly IService service;
        public LoggingProvider(IService service)
        {
            this.service = service;
        }
    }
    public interface ILoggingProvider
    {
    }

这会在启动时产生错误

“已经为给定密钥Spike.CardPaymentProvider注册了一个组件”

如果我将{Name}(“somename”)添加到CardPaymentProvider注册或ICardPaymentProvider注册,那么它就会启动,但不会为{{{{{{ 1}} - 只是一个普通版本

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您必须在同一注册中定义服务覆盖。而不是:

Component.For<ICardPaymentProvider>().ImplementedBy<CardPaymentProvider>(),
Component.For<CardPaymentProvider>().ServiceOverrides(ServiceOverride.ForKey("service").Eq("secure")),

做的:

Component.For<ICardPaymentProvider>()
         .ImplementedBy<CardPaymentProvider>()
         .ServiceOverrides(ServiceOverride.ForKey("service").Eq("secure")),