我需要使用castle-windsor的Inline Dependencies功能.
我需要在依赖链中注入特定组件.
我有这种情况.
static void Main(string[] args)
{
var container = new Castle.Windsor.WindsorContainer();
container.Register(
Component.For<IHigherBusiness>()
.ImplementedBy<HigherBusiness>()
.DependsOn(Dependency.OnComponent<ILogger, FullDetailLogger>())
);
container.Register(Component.For<ISomeBusiness>()
.ImplementedBy<Business>());
container.Register(Component.For<ILogger>()
.ImplementedBy<FullDetailLogger>().IsFallback());
container.Register(Component.For<ILogger>()
.ImplementedBy<SimpleLogger>());
var business = container.Resolve<IHigherBusiness>();
business.DoSomething();
var logger = container.Resolve<ILogger>();
logger.Log("Some Log... .");
}
与商业…
public interface IHigherBusiness
{
void DoSomething();
}
public class HigherBusiness : IHigherBusiness
{
private ISomeBusiness someBusiness;
public HigherBusiness(ISomeBusiness someBusiness)
{
this.someBusiness = someBusiness;
}
public void DoSomething()
{
someBusiness.DoSomething();
}
}
public interface ISomeBusiness
{
void DoSomething();
}
public class Business : ISomeBusiness
{
private ILogger logger;
public Business(ILogger logger)
{
this.logger = logger;
}
public void DoSomething()
{
logger.Log("Message");
}
}
和记录器……
public interface ILogger
{
void Log(string message);
}
public class SimpleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine("Simple Logger: " + message);
}
}
public class FullDetailLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine("Full detail Logger: " + message);
}
}
结果是:
Simple Logger: Message
Simple Logger: Some Log... .
但我希望这个:
Full detail Logger: Message
Simple Logger: Some Log... .
我怎样才能做到这一点?
最佳答案 DependsOn仅工作一级,因此您必须使业务依赖于特定的ILogger.
你可以这样做:
static void Main(string[] args)
{
var container = new Castle.Windsor.WindsorContainer();
container.Register(
Component.For<IHigherBusiness>()
.ImplementedBy<HigherBusiness>()
.DependsOn(Dependency.OnComponent(typeof(ISomeBusiness),
"BusinessWithExtendedLogger"))
);
container.Register(Component.For<ISomeBusiness>().ImplementedBy<Business>()
.DependsOn(Dependency.OnComponent<ILogger, FullDetailLogger>())
.Named("BusinessWithExtendedLogger")
);
container.Register(Component.For<ISomeBusiness>().ImplementedBy<Business>()
.DependsOn(Dependency.OnComponent<ILogger, SimpleLogger>())
.IsDefault()
);
container.Register(Component.For<ILogger>().ImplementedBy<FullDetailLogger>()
.IsFallback()
);
container.Register(Component.For<ILogger>().ImplementedBy<SimpleLogger>());
var business = container.Resolve<IHigherBusiness>();
business.DoSomething();
var normalBusiness = container.Resolve<ISomeBusiness>();
normalBusiness.DoSomething();
var logger = container.Resolve<ILogger>();
logger.Log("Some Log... .");
Console.ReadKey();
}
返回:
Full detail Logger: Message
Simple Logger: Message
Simple Logger: Some Log… .
仅为IHigherBussiness提供FullDetailLogger