Tuesday, March 12, 2013

Ninject Basics

using Ninject;
class Program
{
 static void Main(string[] args)
 {
  var kernel = new StandardKernel();
  //or, passes in an instance of a class that implements NinjectModule interface
  //var kernel = new StandardKernel(new MyModule());
 
  //manages object lifetime using .InScope(), .InSingletonScope(), InThreadScope(), InTransientScope()
  //.InSingletonScope: shopper and shopper2 are the same object
  kernel.Bind<ICreditCard>().To<MasterCard>().InSingletonScope();
 
  //or, gives binding a name if there are multiple bindings to ICreditCard
  //kernel.Bind<ICreditCard>().To<MasterCard>().Named("MasterCard");
  //kernel.Get<ICreditCard>("MasterCard");
 
  //or, bind to method
  /*
  kernel.Bind<ICreditCard>().ToMethod(context =>
           {
            Console.WriteLine("Creating new card");
            return new MasterCard();
           });
  */
 
  //could rebind ICreditCard to Visa after MasterCard
  //kernel.Rebind<ICreditCard>().To<Visa>();
 
  //no need to bind Shopper class to itself, Ninject takes care of bindings automatically
  var shopper = kernel.Get<Shopper>();
  shopper.Charge();
  Console.WriteLine(shopper.ChargesForCurrentCard);
 
  var shopper2 = kernel.Get<Shopper>();
  shopper2.Charge();
  Console.WriteLine(shopper2.ChargesForCurrentCard);
 
  Console.Read();
 }
}
public class MyModule : NinjectModule
{
 public override void Load()
 {
  Kernel.Bind<ICreditCard>().To<MasterCard>();
 }
}

Reference: John Sonmez's IoC Course on Pluralsight

No comments: