我设置了一个NinjectdependencyResolver类来注入我的IStationKpiRepository。由于我手头上没有足够的数据,因此我试图模拟该对象并通过NinjectdependencyResolver注入它。但是结果就是空值。
有人可以帮我吗?
这里是我要模拟的对象界面:
{
public interface IStationKpiRepository
{
/// <summary>
/// Gets the kpi computed over a period of time for one station.
/// </summary>
Kpi StationKpi(int StationHandle, DateTime StartDate, DateTime EndDate);
/// <summary>
/// Gets the daily kpi over a period of time for one station.
/// </summary>
IEnumerable<Kpi> StationKpiHistory(int StationHandle, DateTime StartDate, DateTime EndDate);
}
这里是NinjectDependencyResolver类:
namespace MyApp.WebUI.Infrastructure
{
/// <summary>
/// The NinjectDependencyResolver class.
/// </summary>
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernelParam)
{
kernel = kernelParam;
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
// creating a mock object for the kpi
DateTime startDate = new DateTime(2018, 01, 01);
DateTime endDate = DateTime.Now;
int stationHandle = 32;
List<Kpi> kpis = new List<Kpi>();
Random r = new Random();
foreach (DateTime day in Tools.EachDay(startDate, endDate))
{
kpis.Add(
new Kpi
{
StationHandle = stationHandle,
StartDateTime = day.Date.Add(new TimeSpan(0, 0, 0)),
EndDateTime = day.Date.Add(new TimeSpan(23, 59, 59)),
Rates = new Rates { TEEP = r.NextDouble(), GEE = r.NextDouble(), OEE = r.NextDouble(), Performance = r.NextDouble(), Quality = r.NextDouble(), Requisition = r.NextDouble(), Load = r.NextDouble(), Involvement = r.NextDouble(), HardwareAvailability = r.NextDouble() },
Times = new Times { AT = r.Next(10000), OT = r.Next(10000), PPT = r.Next(10000), RT = r.Next(10000), NRT = r.Next(10000), FPT = r.Next(10000), FT = r.Next(10000), MTBF = r.Next(10000), MTTR = r.Next(10000) }
}
);
};
Mock<IStationKpiRepository> kpiMock = new Mock<IStationKpiRepository>();
kpiMock.Setup(k => k.StationKpiHistory(stationHandle, startDate, endDate)).Returns(ProConnect.Domain.Concrete.Dummies.GetStationKpiHistory(stationHandle, startDate, endDate));
kpiMock.Setup(k => k.StationKpi(stationHandle, startDate, endDate)).Returns(Dummies.GetStationKpi(stationHandle, startDate, endDate));
//kpiMock.SetReturnsDefault(kpis);
// injecting the kpi mock object. DOES NOT WORK...
kernel.Bind<IStationKpiRepository>().ToConstant(kpiMock.Object);
// injecting the real kpi object coming. This works when uncommented.
//kernel.Bind<IStationKpiRepository>().To<CWorkStationKpiRepository>();
}
}
}