// 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 StructureMap; using StructureMap.Attributes; 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; [SetterProperty] public IDemo Demo { get { return _demo; } set { _demo = value; } } public void Test() { Console.Write(this.GetType().FullName + ": "); _demo.Test(); } } public class Program { public static void Main(string[] args) { // non DI IDemo o1 = new Demo(); o1.Test(); // setup ObjectFactory.Initialize(x => { x.For().Use(); x.For().AlwaysUnique().Use(); x.For().Singleton().Use(); x.For().Use(); x.For().Use(); }); // simple IDemo o2 = ObjectFactory.GetInstance(); o2.Test(); // scope for(int i = 0; i < 3; i++) { IDedicated o3 = ObjectFactory.GetInstance(); o3.Test(); } for(int i = 0; i < 3; i++) { IShared o4 = ObjectFactory.GetInstance(); o4.Test(); } // auto wire ICTor o5 = ObjectFactory.GetInstance(); o5.Test(); IProps o6 = ObjectFactory.GetInstance(); o6.Test(); } } }