如何更新已注册的服务 Castle Windsor

How to update already registered service Castle Windsor

我是 DI 容器的初学者。

我正在使用第三方框架,它有一个 class 如下所示

public class PurchaseOrderAppService : IPurchaseOrderAppService, IAutoRegister
    {
        private readonly IEmail _email;

        public PurchaseOrderAppService(IEmail email)
        {
            _email = email;
        }
    }

所有继承IAutoRegister接口的class类都由第三方框架自动注册。 电子邮件 class 如下所示

public class Email : IEmail, IAutoRegister
{
    public Send(string message)
    {
        //Send a message
    }
}

我想要的是 PurchaseOrderAppService class 使用另一个名为 MyEmail 的 class 而不是 Email。

public class MyEmail : IEmail
{
    public Send(string message)
    {
        //Send a message another way
    }
}

如何通过框架更新已经注册的服务?

谢谢。

更新注册服务不是处理 IoC 容器的正确方法,也不是您需要的。我建议你看看 https://github.com/castleproject/Windsor/blob/master/docs/inline-dependencies.md and https://github.com/castleproject/Windsor/blob/master/docs/registering-components-one-by-one.md#supplying-the-component-for-a-dependency-to-use-service-override

感谢@Thuan,

在第二个 link 中,有一个名为 ServiceOverrides 的方法已过时,我可以改用 DependsOn

IocContainer.Register(
    Component.For<IEmail>()
    .ImplementedBy<MyEmail>()
    .Named("Email.MyEmail"),
    Component.For<IPurchaseOrderAppService>()
    .ImplementedBy<PurchaseOrderAppService>()
    .Named("PurchaseOrderAppServiceWithMyEmail").IsDefault()
    .DependsOn(Dependency.OnComponent(typeof(IEmail), "Email.MyEmail")));