【发布时间】:2015-04-24 13:02:56
【问题描述】:
我的所有类都实现了一个接口,这些类负责将数据导出为不同的格式。
示例代码:
public interface IExport
{
string Exporter();
}
public class ExcelExport : IExport
{
public string Exporter()
{
return "excel";
}
}
public class PdfExport : IExport
{
public string Exporter()
{
return "pdf";
}
}
我想在运行时得到一个特定的类型,所以我知道我必须使用抽象工厂,但我不知道在这个例子中如何 tp。
导出由管理器类处理:
public interface IExportManager
{
IExport GetExportProvider(ExportType type);
}
public interface IExportFactory
{
IExport CreateExport(ExportType type);
}
public class ExportManager : IExportManager
{
private IExportFactory exportFactory;
public ExportManager(IExportFactory exportFactory)
{
this.exportFactory = exportFactory;
}
public IExport GetExportProvider(ExportType type)
{
return exportFactory.CreateExport(type);
}
}
public enum ExportType
{
PDF,
XLSX
}
如何使用 GetExportProvider 方法根据类型参数获取正确的对象实例?
这是我的 Ninject 模块:
public class NinModule : NinjectModule
{
public override void Load()
{
this.Bind<IExportFactory>().ToFactory();
this.Bind<IExportManager>().To<ExportManager>();
this.Bind<IExport>().To<ExcelExport>();//.WhenInjectedInto<IExportManager>().WithPropertyValue("type", ExportType.XLSX);
this.Bind<IExport>().To<PdfExport>();//.WhenInjectedInto<IExportManager>().WithPropertyValue("type", ExportType.PDF);
}
}
以及用于测试它的代码:
static void Main(string[] args)
{
IKernel k = new StandardKernel(new NinModule());
IExportManager r = k.Get<IExportManager>();
var pdf = r.GetExportProvider(ExportType.PDF);
Console.WriteLine(pdf.Exporter());
Console.Read();
}
提前感谢您的帮助。
【问题讨论】:
标签: c# ninject inversion-of-control ioc-container