// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using Ninject; using Ninject.Modules; namespace E { public interface IBase { void Test(); } public class Base : IBase { public virtual void Test() { Console.WriteLine("I am " + this.GetType().FullName); } } public interface IDemo : IBase { } public class Demo : Base, IDemo { } public interface IDedicated : IBase { } public class Dedicated : Base, IDedicated { private int n; private static int tot = 0; public Dedicated() { tot++; n = tot; } public override void Test() { Console.Write(n + " of " + tot + ": "); base.Test(); } } public interface IShared : IBase { } public class Shared : Base, IShared { private int n; private static int tot = 0; public Shared() { tot++; n = tot; } public override void Test() { Console.Write(n + " of " + tot + ": "); base.Test(); } } public interface ICTor { void Test(); } public class CTor : ICTor { private IDemo _demo; public CTor(IDemo demo) { _demo = demo; } public void Test() { Console.Write(this.GetType().FullName + ": "); _demo.Test(); } } public interface IProps { void Test(); } public class Props : IProps { private IDemo _demo; [Inject] public IDemo Demo { get { return _demo; } set { _demo = value; } } public void Test() { Console.Write(this.GetType().FullName + ": "); _demo.Test(); } } public class Special : NinjectModule { public override void Load() { Bind().To(); } } public class Program { public static void Main(string[] args) { // non DI IDemo o1 = new Demo(); o1.Test(); // setup IKernel krnl = new StandardKernel(); krnl.Bind().To(); krnl.Bind().To().InTransientScope(); krnl.Bind().To().InSingletonScope(); krnl.Bind().To(); krnl.Bind().To(); // base IDemo o2 = krnl.Get(); o2.Test(); // scope for(int i = 0; i < 3; i++) { IDedicated o3 = krnl.Get(); o3.Test(); } for(int i = 0; i < 3; i++) { IShared o4 = krnl.Get(); o4.Test(); } // auto wire ICTor o5 = krnl.Get(); o5.Test(); IProps o6 = krnl.Get(); o6.Test(); // module IKernel mkrnl = new StandardKernel(new Special()); IBase o7 = mkrnl.Get(); o7.Test(); } } }