c# - 注册默认的 CaSTLe Windsor 组件,同时允许自定义组件

标签 c# dependency-injection castle-windsor

我正在尝试使用 CaSTLe Windsor 实现基于约定的注册,但我不知道如何处理交换服务的默认实现。

在我的框架中,我可能有一个服务接口(interface)和一个默认实现:

public interface ILogger
{
     void Info(string message);
}

public class Logger : ILogger
{
     public void Info(string message)
     {
         Console.WriteLine(message);
     }
}

在典型的用例中,我希望 CaSTLe Windsor 使用 ILogger 服务注册 Logger。

但是,在某些用例中,客户端代码可能会提供 ILogger 的替代实现:

public class CustomLogger : ILogger
{
    public void Info(string message)
    {
         Console.WriteLine("[LOG]: {0}", message);
    }
}

在此用例中,我希望 CaSTLe Windsor 使用 ILogger 服务而不是 Logger 注册 CustomLogger。

到目前为止,我已经尝试过类似分层方法的方法,我尝试注册所有默认接口(interface),然后注册非默认接口(interface):

using (var container = new WindsorContainer())
{
    container.Register(
        Classes.FromAssemblyInDirectory(new AssemblyFilter(pluginDirectoryPath))
            .Where(type => true)
            .WithService.DefaultInterfaces(), 
        Classes.FromAssemblyInDirectory(new AssemblyFilter(pluginDirectoryPath))
            .Where(type => true)
            .WithService.AllInterfaces());

    var logger = container.Resolve<ILogger>();
    logger.Info("hello, world!");
}

但是,这似乎不起作用,因为 Logger 和 CustomLogger 都注册到 ILogger,但当我解析 ILogger 时,我仍然得到 Logger。有关如何执行此操作的任何提示?

此外,我无法单独注册每个组件和服务,因为组合根是与客户端代码分开的自己的可执行文件,因此在不进行程序集扫描的情况下,它对哪些服务可用的了解非常有限。

最佳答案

首先注册会获胜,所以...只需先注册您的非默认实现,然后注册您的默认实现即可填补空白。

关于c# - 注册默认的 CaSTLe Windsor 组件,同时允许自定义组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29089420/

相关文章:

c# - 如何检查浏览器是否在网络应用程序中启用了 cookie?

c# - 是否有将对象转换为小数的单行方法?

php - Symfony - 使用服务工厂还是服务配置器更好?

caSTLe-windsor - 是否有温莎城堡的最新入门指南?

dependency-injection - 使用 CaSTLe Windsor 解析 HttpControllerContext

wcf - 在 CaSTLe.Windsor 中将客户端基于任务的操作与 WCFFacility 结合使用

c# - 反序列化 PSON 文件

c# - PredicateBuilder "And"方法不起作用

dependency-injection - 忍者2.0 : Property Injection without attribute

c# - 以相同的 ConfigureServices 方法访问在 asp.net core 的 startup.cs 文件中的 ConfigureServices 中创建的单例