NInject Example

I started looking at NInject do handle the dependency injection that I normally do by hand.   To that end, I spun up the project that I used for my last foray into the world of dependency injection:

  1. public interface IAnimal
  2. {
  3.     void Talk();
  4.     void Eat();
  5. }

 

And

 

  1. public class Elephant: IAnimal
  2. {
  3.     public void Talk()
  4.     {
  5.         Console.WriteLine("Trumpet");
  6.     }
  7.  
  8.     public void Eat()
  9.     {
  10.         Console.WriteLine("Yummy Peanuts");
  11.     }
  12. }
  13.  
  14. public class Seal: IAnimal
  15. {
  16.     public void Talk()
  17.     {
  18.         Console.WriteLine("Ark Ark");
  19.     }
  20.  
  21.     public void Eat()
  22.     {
  23.         Console.WriteLine("Yummy Fish");
  24.     }
  25. }

 

Mow, instead of using Activator.CreateInstance, I am going to use NInject to do the mapping,  To that end, I installed NInject via NuGet

image

I then coded up the example for the on-line tutorial using the StandardKernal class like so

  1. static void Main(string[] args)
  2. {
  3.     IKernel kernel = new StandardKernel();
  4.     IAnimal animal = kernel.Get<Elephant>();
  5.     animal.Talk();
  6.     animal.Eat();
  7.     Console.ReadKey();
  8. }

 

and sure enough

image

So this is good stuff.  I think NInject and MOQ are my two favorite new tools in the toolbox…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: