Understanding Ninject with a more complex scenario

扶醉桌前 提交于 2019-12-13 02:43:56

问题


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


来源:https://stackoverflow.com/questions/12432096/understanding-ninject-with-a-more-complex-scenario

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!