我正在尝试使用 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/