Understanding Ninject with a more complex scenario

2019-08-17 08:19发布

问题:

I am trying to use ninject to.. well do what ninject does..

Basically the injection isnt happening.

In my code below I am creating the Kernel in my "test" and expecting an IDrinkCan implementation to somehow get into my CokeComsumer class.

I think i have missed something here.. since the IDrinkCan is null when I put a break point on the CokeConsumer constructor.

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

回答1:

This is wrong!!

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

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

I should be getting the CokeConsumer from the kernel!!!!

i.e.

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