0
我正在嘗試使用ninject來...做好ninject的工作..用更復雜的場景瞭解Ninject
基本上注入不會發生。
在我的代碼中,我在我的「測試」中創建內核,期望一個IDrinkCan實現以某種方式進入我的CokeComsumer類。
我想我錯過了這裏的東西..因爲當我在CokeConsumer構造函數上放置一個斷點時,IDrinkCan爲null。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using Ninject.Modules;
using NUnit.Framework;
namespace testThing
{
public class MyDependencyKernel
{
public static IKernel DependencyKernel { get; internal set; }
public MyDependencyKernel()
{
DependencyKernel = new StandardKernel(new MyNinjectModule());
}
public MyDependencyKernel(NinjectModule ninjectModule)
{
DependencyKernel = new StandardKernel(ninjectModule);
}
}
public class MyNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IDrinkCan>().To<Coke>();
}
}
public interface IDrinkCan
{
void OpenCan(int canSize);
void DrinkSome(int milliletres);
bool IsEmpty();
}
public class Coke : IDrinkCan
{
private int _capacity;
private bool _isEmpty;
public void OpenCan(int canSize)
{
_capacity = canSize;
}
public void DrinkSome(int milliletres)
{
if (!_isEmpty) _capacity -= milliletres;
if (_capacity < 0) _isEmpty = true;
}
public bool IsEmpty()
{
return _isEmpty;
}
}
public class CokeConsumer
{
//[Inject]
public IDrinkCan Drink { get; set; }
[Inject] //drink is not being injected
public CokeConsumer(IDrinkCan drink)
{
Drink = drink;
Drink.OpenCan(330);
}
public CokeConsumer()
{
Drink.OpenCan(330);
}
public void DrinkSomeCoke(int amount)
{
Drink.DrinkSome(amount);
}
}
[TestFixture]
public class SomeTestClass
{
[Test]
public void DoSomeTest()
{
MyDependencyKernel kernel = new MyDependencyKernel();
CokeConsumer steve = new CokeConsumer();
steve.DrinkSomeCoke(100);
}
}
}