Пример #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var a = typeof(Foo).GetConstructors();

            Console.WriteLine(1);

            var root = new Cat()
                       .Register <IFoo, Foo>(Lifetime.Transient)
                       .Register <IBar>(_ => new Bar(), Lifetime.Self)
                       .Register <IBaz, Baz>(Lifetime.Root);

            var cat1 = root.CreateChild();
            var cat2 = root.CreateChild();

            void GetServices <TService>(Cat cat)
            {
                cat.GetService <TService>();
                cat.GetService <TService>();
            }

            GetServices <IFoo>(cat1);
            GetServices <IBar>(cat1);
            GetServices <IBaz>(cat1);
            Console.WriteLine();


            GetServices <IFoo>(cat2);
            GetServices <IBar>(cat2);
            GetServices <IBaz>(cat2);

            //
            Console.WriteLine(2);
            var myNewCat = new Cat()
                           .Register <IFoo, Foo>(Lifetime.Transient)
                           .Register <IBar, Bar>(Lifetime.Transient)
                           .Register(typeof(IFoobar <,>), typeof(FooBar <,>), Lifetime.Transient);
            var foobar = (FooBar <IFoo, IBar>)myNewCat.GetService <IFoobar <IFoo, IBar> >();

            Debug.Assert(foobar.Foo is Foo);
            Debug.Assert(foobar.Bar is Bar);


            //
            Console.WriteLine(3);

            var services = new Cat().Register <Base, Foo>(Lifetime.Transient)
                           .Register <Base, Bar>(Lifetime.Transient)
                           .Register <Base, Baz>(Lifetime.Transient)
                           .GetServices <Base>();

            Debug.Assert(services.OfType <Foo>().Any());
            Debug.Assert(services.OfType <Bar>().Any());
            Debug.Assert(services.OfType <Baz>().Any());

            Console.WriteLine(4);

            using (var anotherRoot = new Cat().Register <IFoo, Foo>(Lifetime.Transient)
                                     .Register <IBar, Bar>(Lifetime.Self)
                                     .Register <IBaz, Baz>(Lifetime.Root))
            {
                using (var cat = anotherRoot.CreateChild())
                {
                    cat.GetService <IFoo>();
                    cat.GetService <IBar>();
                    cat.GetService <IBaz>();
                }
                Console.WriteLine("Child cat is disposed.");
            }
            Console.WriteLine("Root cat is disposed.");

            Console.WriteLine(".........................Test DI..............");
            TestDI();

            TestDI_Dispose();
        }