开发者

Constructor Inject with Ninject 2

开发者 https://www.devze.com 2023-03-02 13:58 出处:网络
I\'ve used Ninject with MVC3 for automagic inject of constructor arguments.It worked great. How do you do something similar with non-MVC code.

I've used Ninject with MVC3 for automagic inject of constructor arguments. It worked great.

How do you do something similar with non-MVC code.

For example:

public class Ninja
{
    private readonly IWeapon _weapon;
    public Ninja(IWeapon weapon)
    {
        _weapon = weapon;
    }

    public void Strike()
    {
        _weapon.Strike();
    }
}


public class MyProgram
{
    public void DoStuff()
    {
        var Ninja = new Ninja(); // I'm wanting Ninject to call the parameterized Ninja constructor
        ninja.St开发者_Go百科rike();
    }

}

How would I alter the code to get it to work?


public interface IWeapon
{
    void Strike();
}

public class Sword : IWeapon
{
    public void Strike()
    {
        Console.WriteLine("black ninja strike");
    }
}

public class Ninja
{
    private readonly IWeapon _weapon;
    public Ninja(IWeapon weapon)
    {
        _weapon = weapon;
    }

    public void Strike()
    {
        _weapon.Strike();
    }
}

public class WarriorModule : NinjectModule
{
    public override void Load()
    {
        Bind<IWeapon>().To<Sword>();
    }
}


class Program
{
    static void Main()
    {
        var kernel = new StandardKernel(new WarriorModule());
        var ninja = kernel.Get<Ninja>();
        ninja.Strike();
    }
}


Wouldn't it just be:

var ninja = Kernel.Get<Ninja>();

You obviously have to resolve the dependency though Ninject.


You need to have an instance of StandardKernel let's call it kernel and then use kernel.Get<Ninja>(). This works since Ninja is non abstract, so it is considered bound to itself. Obviously some concrete types needs to be bound to IWeapon to allow NInject to create Ninja.

0

精彩评论

暂无评论...
验证码 换一张
取 消