我正在做一些使用NInject来理解注入的例子......
但最终注射混乱......
例如: -
考虑以下示例: -
class Busineesss
{
FirstInterface targetInter = null;
[Inject] //Setter Injection
public SecondInterface ProInj { get; set; }
[Inject] //Ctor Injection
public Busineesss(FirstInterface inbound)
{
targetInter = inbound;
}
public void run()
{
/*Line:X*/ targetInter.doSomeThing();
/*Line:Y*/ ProInj.GetSomethingMyName();
}
}
interface FirstInterface
{
void doSomeThing();
}
interface SecondInterface
{
void GetSomethingMyName();
}
模块和主要:
public class Module : NinjectModule
{
public override void Load()
{
Bind<FirstInterface>().To<FirstImplementer>();
Bind<SecondInterface>().To<SecondImplementer>();
}
}
static void Main(string[] args)
{
StandardKernel std = new StandardKernel();
std.Load(Assembly.GetExecutingAssembly());
FirstInterface obj = std.Get<FirstInterface>();
Busineesss b = new Busineesss(obj); //Injecting Ctor data here
b.run();
}
我的理解: - 因此,根据我的理解,我们必须手动调用具有必要数据的根类,然后Ninject将自己解决剩余的依赖关系。
但我没有得到任何这样的东西。我只在 ProInj.GetSomethingMyName() 一行获得Null Exception。
你的朋友可以帮助我,理解这个,所以我可以多抓一点......
提前致谢..
答案 0 :(得分:2)
问题是当你应该从容器中解析它时new
Busineesss
FirstInterface obj = std.Get<FirstInterface>();
Busineesss b = new Busineesss(obj);
服务。替换:
Busineesss b = std.Get<Busineesss>();
使用:
// All cards:
var cards = [
'https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/Playing_card_club_A.svg/2000px-Playing_card_club_A.svg.png',
'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Playing_card_spade_2.svg/819px-Playing_card_spade_2.svg.png',
'http://www.clipartbest.com/cliparts/9T4/ezn/9T4eznrjc.png',
];
function play() {
// get random position. Math.random returns float between 0 and 1
var p1 = Math.floor(Math.random() * cards.length); // will get integet between 0 and cards.length - 1
var p2 = Math.floor(Math.random() * cards.length);
// create new image element
var img1 = document.createElement('img');
var img2 = document.createElement('img');
// set image source to be same as selected card
img1.src = cards[p1];
img2.src = cards[p2];
// select cards holding elements
var holder1 = document.getElementById('card1');
var holder2 = document.getElementById('card2');
// clear images from previous game
holder1.innerHTML = "";
holder2.innerHTML = "";
// add images to it's holders
holder1.appendChild(img1);
holder2.appendChild(img2);
// game logic. Compare array key to see who wins
if (p1 > p2) {
alert('Player 1 is winner!');
} else if (p1 < p2) {
alert('Player 2 is winner!');
} else {
alert('No winner!');
}
}
应该解决你的问题。