了解Ninject具有更复杂的场景(Understanding Ninject with a mor

2019-10-28 15:12发布

我试图用ninject来..好做ninject做了什么..

基本上,注射心不是发生。

在我下面的代码,我在我的“测试”创建内核,并预期IDrinkCan实现以某种方式进入我CokeComsumer类。

我想,我已经在这里错过了什么。自IDrinkCan为空,当我把一个破发点上CokeConsumer构造。

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);
    }
}
}

Answer 1:

这是不对的!

[Test]
public void DoSomeTest()
{
    MyDependencyKernel kernel = new MyDependencyKernel();

    CokeConsumer steve = new CokeConsumer();
    steve.DrinkSomeCoke(100);
}

我应该从内核得到CokeConsumer !!!!

var steve = kernel.DependencyKernel.Get<CokeConsumer>();


文章来源: Understanding Ninject with a more complex scenario