问题描述
而在温莎城堡注册组件,我们怎么绑定具体实现的接口到具有该接口上的依赖关系的组件。我提前知道哪个实现需要由组件使用。
While registering components in Castle Windsor, how do we bind specific implementation of an interface to a component that has a dependency on that interface. I know in advance which implementation needs to be used by the component.
例如我创建的基础上,从多个博客和教程代码示例控制台应用程序。
For example i created a sample console application based on code from several blogs and tutorials.
以下是代码。
public interface IReport
{
void LogReport();
}
public interface ILogger
{
string Log();
}
public class FileLogger : ILogger
{
public string Log()
{
return "Logged data to a file";
}
}
public class DatabaseLogger : ILogger
{
public string Log()
{
return "Logged data to a database";
}
}
public class McAfeeService : IReport
{
private readonly ILogger _logger;
public McAfeeService(ILogger logger)
{
this._logger = logger;
}
public void LogReport()
{
string getLogResult = this._logger.Log();
Console.WriteLine("McAfee Scan has " + getLogResult);
}
}
public class NortonService : IReport
{
private readonly ILogger _logger;
public NortonService(ILogger logger)
{
this._logger = logger;
}
public void LogReport()
{
string getLogResult = this._logger.Log();
Console.WriteLine("Norton Scan has " + getLogResult);
}
}
class Program
{
private static IWindsorContainer container;
static void Main(string[] args)
{
// Register components
container = new WindsorContainer();
container.Register(Component.For<IReport>().ImplementedBy<NortonService>());
container.Register(Component.For<ILogger>().ImplementedBy<FileLogger>());
IReport service = container.Resolve<IReport>();
service.LogReport();
Console.ReadLine();
}
}
我想NortonService始终使用Filelogger和McAfeeService使用一个数据库记录器。
I would like NortonService to always use a Filelogger and McAfeeService to use a Database Logger.
在上面的程序我无法NortonService绑定到FileLogger。
In the above program i am unable to bind NortonService to FileLogger.
如何?做
推荐答案
上面的回答使我内联依赖和功能的
The above answers lead me to inline dependencies and the feature service override
下面是注册码
container.Register(Component.For<IReport>().ImplementedBy<NortonService>().Named("nortonService"));
container.Register(Component.For<ILogger>().ImplementedBy<FileLogger>());
container.Register(Component.For<ILogger>().ImplementedBy<DatabaseLogger>());
container.Register(
Component.For<IReport>().ImplementedBy<McAfeeService>().Named("mcafeeService")
.DependsOn(Dependency.OnComponent<ILogger, DatabaseLogger>())
);
IReport mcafeescan = container.Resolve<IReport>("mcafeeService");
mcafeescan.LogReport();
IReport nortonscan = container.Resolve<IReport>("nortonService");
nortonscan.LogReport();
输出:
Output:
迈克菲扫描已登录数据到数据库
诺顿扫描已记录的数据到一个文件
McAfee Scan has Logged data to a databaseNorton Scan has Logged data to a file
这篇关于温莎城堡 - 多种实现一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!