Api 如何使用Ninject连接/绑定多个实现?
我正在创建一个API,我想公开一个名为IReportFields的接口,我想让客户端实现这个类,基本上从任何数据源(通常是数据库)获取字段 在我的IReport接口中,我想获取一个IReportFields实例(可能不止一个,在我的应用程序中,我至少有4个),然后在该接口中执行我需要执行的任何操作,通常是构建报告之类的操作 例如:Api 如何使用Ninject连接/绑定多个实现?,api,dependency-injection,c#-3.0,ninject,Api,Dependency Injection,C# 3.0,Ninject,我正在创建一个API,我想公开一个名为IReportFields的接口,我想让客户端实现这个类,基本上从任何数据源(通常是数据库)获取字段 在我的IReport接口中,我想获取一个IReportFields实例(可能不止一个,在我的应用程序中,我至少有4个),然后在该接口中执行我需要执行的任何操作,通常是构建报告之类的操作 例如: public interface IReportField { ICollection<ReportField> GetFields(); } 问题:
public interface IReportField
{
ICollection<ReportField> GetFields();
}
问题:
IReportFields可以有多个实现,即许多不同类型的字段,如何调用方法GetReport记住我正在使用Ninject,如何将接口连接在一起
//这一点是我被卡住的地方,我如何传递参数,因为我不想对一个需要我得到报告的类有太大的依赖性
您可以使用
Constructor
injection将所有的IFieldReports
连接起来,例如您的连接如下:
IKernel kernel = new StandardKernel();
kernel.Bind<IReportField>().To<FieldImp1>();
kernel.Bind<IReportField>().To<FieldImp2>();
kernel.Bind<IReport>().To<ReportImpl>();
如果我弄错了,请告诉我我是否可以取消fo并获取我添加到内核中的所有IReportField实现,而不必将其提供给IReport?我不知道这是可能的?请重新措辞。我不明白你的意思
IFieldReport field1 = new FieldImp1();
IFieldReport field2 = new FieldImp2();
var report = GetReport(feild1, field2);
IKernel kernel = new StandardKernel();
kernel.Bind<IReportField>().To<FieldImp1>();
kernel.Bind<IReportField>().To<FieldImp2>();
kernel.Bind<IReport>().To<ReportImpl>();
public class ReportImpl : IReport
{
public ReportImpl(List<IReportField> fieldReports)
{
// you now have all the wires to IReportField in fieldReports parameter
foreach(IReportField fieldReport in fieldReports)
{
var fields = fieldReport.GetFields();
// do whatever with the fields
}
}
}