Ejemplo n.º 1
0
        public void TestComplexExpression()
        {
            var newGenerator = new ConstructorExpressionGenerator(ConstructorSelectors.MostSpecific);
            int numFoos = 0;
            var fooGenerator = new LambdaExpressionGenerator(() => { numFoos++; return new ServiceFoo(); });
            var singleBar = new ServiceBar(new ServiceFoo());
            var barGenerator = new ConstantExpressionGenerator(singleBar);

            newGenerator.DependencyExpressionGenerating += (sender, args) =>
                {
                    IExpressionGenerator generator;
                    if (args.DependencyType == typeof(ServiceFoo))
                        generator = fooGenerator;
                    else if (args.DependencyType == typeof(ServiceBar))
                        generator = barGenerator;
                    else
                        generator = (IExpressionGenerator)sender;

                    args.Expression = generator.GenerateExpression(args.DependencyType);
                };

            var expression = newGenerator.GenerateExpression(typeof(Root));

            var func = Expression.Lambda<Func<Root>>(expression).Compile();

            var r = func();

            Assert.IsNotNull(r);
            Assert.IsNotNull(r.Bar);
            Assert.IsNotNull(r.Foo);
            Assert.Greater(numFoos, 0);
            Assert.AreSame(r.Bar, singleBar);
            Assert.AreSame(r.Bar.Foo, singleBar.Foo);
            Assert.AreNotSame(r.Foo, r.Bar.Foo);
            Assert.AreNotSame(r.Foo, singleBar.Foo);
        }
Ejemplo n.º 2
0
        public void TransientProducerWithConstantExpressionShouldReturnSame()
        {
            var o1 = new object();
            IExpressionGenerator generator = new ConstantExpressionGenerator(o1);
            IInstanceProvider provider = new TransientInstanceProvider(typeof(object), generator);

            var o2 = provider.GetInstance();

            Assert.NotNull(o2);
            Assert.AreSame(o1, o2);

            // Stupid, but let's be sure
            foreach (var obj in Enumerable.Range(0, 100).Select(i => provider.GetInstance()))
                Assert.AreSame(o1, obj);
        }