Adam Tegen
Adam Tegen

Reputation: 25887

Constructor Inject with Ninject 2

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.Strike();
    }

}

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

Upvotes: 1

Views: 2656

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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

Upvotes: 5

Felice Pollano
Felice Pollano

Reputation: 33252

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.

Upvotes: 1

Claus J&#248;rgensen
Claus J&#248;rgensen

Reputation: 26347

Wouldn't it just be:

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

You obviously have to resolve the dependency though Ninject.

Upvotes: 4

Related Questions