给定以下代码:
public interface IMyContext
{
string subtype { get; set; }
}
public class MyContext : IMyContext
{
public string subtype { get; set; }
}
public interface IMyExporter
{
string Export();
}
public class MyExporterXML : IMyExporter
{
public string Export()
{
return "";
}
}
public class MyExporterJson : IMyExporter
{
public string Export()
{
return "";
}
}
public class MyExporterFactory
{
private IMyContext context;
public MyExporterFactory(IMyContext context)
{
this.context = context;
}
public IMyExporter Create()
{
switch (context.subtype)
{
case "JSON" :
return new MyExporterJson();
default:
return new MyExporterXML();
}
}
}
public class MyService
{
private IMyContext context;
private IMyExporter exporter;
public MyService(IMyContext context, IMyExporter exporter)
{
this.context = context;
this.exporter = exporter;
}
public string Extractdata()
{
return exporter.Export();
}
}
[TestClass]
public class UnitTest2
{
[TestMethod]
public void TestMethod1()
{
var container = new WindsorContainer();
container.Register(Component.For<IMyContext>().ImplementedBy<MyContext>());
container.Register(Component.For<MyExporterFactory>());
container.Register(Component.For<MyService>());
container.Register(Component.For<IMyExporter>().UsingFactoryMethod(kernel => kernel.Resolve<MyExporterFactory>().Create()));
var context = container.Resolve<IMyContext>();
var service = container.Resolve<MyService>();
context.subtype = "JSON";
service.Extractdata();
}
}
有没有办法让 MyService 中注入的导出器在实际使用时解析?IE。运行上述代码时,导出器解析为 MyExporterXML,但由于 context.subtype = "JSON" 设置,我真的希望它是 MyExporterJson。但是,导出器在设置子类型之前就已解决...
我知道 Castle::Windsor 有一些称为基于委托的工厂,但我根本不知道如何使用它....
任何帮助将不胜感激,TIA
索伦