Exemple #1
0
        public ServiceFamily Build(Type type, ServiceGraph serviceGraph)
        {
            if (!type.Closes(typeof(ILogger <>)))
            {
                return(null);
            }

            var inner      = type.GetGenericArguments().Single();
            var loggerType = typeof(Logger <>).MakeGenericType(inner);

            Instance instance = null;

            if (inner.IsPublic)
            {
                instance = new ConstructorInstance(type, loggerType,
                                                   ServiceLifetime.Transient);
            }
            else
            {
                instance = new LambdaInstance(type, provider =>
                {
                    var factory = provider.GetService <ILoggerFactory>();
                    return(Activator.CreateInstance(loggerType, factory));
                }, ServiceLifetime.Transient);
            }

            return(new ServiceFamily(type, instance));
        }
Exemple #2
0
 public virtual void InvokeConstructor(ConstructorInstance constructor)
 {
     if (mv != null)
     {
         mv.InvokeConstructor(constructor);
     }
 }
Exemple #3
0
        public object QuickBuild(Type objectType)
        {
            assertNotDisposed();

            if (!objectType.IsConcrete())
            {
                throw new InvalidOperationException("Type must be concrete");
            }

            var ctor = new ConstructorInstance(objectType, objectType, ServiceLifetime.Transient).DetermineConstructor(ServiceGraph, out var message);

            if (ctor == null)
            {
                throw new InvalidOperationException(message);
            }

            var dependencies = ctor.GetParameters().Select(x =>
            {
                var instance = ServiceGraph.FindInstance(x);



                return(instance.QuickResolve(this));
            }).ToArray();

            return(ctor.Invoke(dependencies));
        }
Exemple #4
0
 public virtual void NewInstance(ConstructorInstance constructor, Script argumentsScript)
 {
     if (mv != null)
     {
         mv.NewInstance(constructor, argumentsScript);
     }
 }
Exemple #5
0
            public ConstructorInstance Add(Type implementationType)
            {
                var instance = new ConstructorInstance(_serviceType, implementationType, ServiceLifetime.Transient);

                _parent.Add(instance);
                return(instance);
            }
        public void hashcode_logic()
        {
            var instance1 = new ConstructorInstance(typeof(IWidget), typeof(AWidget), ServiceLifetime.Transient)
            {
                Name = "One"
            };

            var instance2 = new ConstructorInstance(typeof(IWidget), typeof(AWidget), ServiceLifetime.Transient)
            {
                Name = "Two"
            };

            var instance3 = new ConstructorInstance(typeof(AWidget), typeof(AWidget), ServiceLifetime.Transient)
            {
                Name = "One"
            };

            var instance4 = new ConstructorInstance(typeof(IWidget), typeof(AWidget), ServiceLifetime.Transient)
            {
                Name = "One"
            };

            instance1.GetHashCode().ShouldBe(instance4.GetHashCode());

            instance1.GetHashCode().ShouldNotBe(instance2.GetHashCode());
            instance1.GetHashCode().ShouldNotBe(instance3.GetHashCode());
            instance2.GetHashCode().ShouldNotBe(instance3.GetHashCode());
        }
Exemple #7
0
        public void find_dependencies_deep()
        {
            var theServices = new ServiceRegistry();

            theServices.AddTransient <IWidget, AWidget>();
            theServices.AddTransient <Rule, BlueRule>();
            theServices.AddTransient <OtherGuy>();
            theServices.AddTransient <GuyWithWidgetAndRule>();

            var theGraph = new ServiceGraph(theServices, Scope.Empty());

            theGraph.Initialize();

            var instance = ConstructorInstance.For <GuyWithGuys>();

            instance.CreatePlan(theGraph);

            var expected = new[]
            {
                typeof(AWidget),
                typeof(BlueRule),
                typeof(OtherGuy),
                typeof(GuyWithWidgetAndRule)
            };


            instance.Dependencies.OfType <ConstructorInstance>()
            .Select(x => x.ImplementationType)
            .ShouldBe(expected, true);
        }
Exemple #8
0
        protected void ImplementCascadeLoadMode()
        {
            FieldInstance f_cascadeLoadMode = ImplementField(new FieldInstance(FieldAttributes.Private, "__cascadeLoadMode", typeof(CascadeLoadMode)));

            ImplementGetter(template_m_getCascadeLoadMode, f_cascadeLoadMode);
            ImplementSetter(template_m_setCascadeLoadMode, f_cascadeLoadMode);

            ConstructorInfo[] constructors = State.CurrentType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
            for (int a = constructors.Length; a-- > 0;)
            {
                ConstructorInstance ci = new ConstructorInstance(constructors[a]);
                ci = new ConstructorInstance(MethodAttributes.Public, ci.Parameters);
                IMethodVisitor mv = VisitMethod(ci);
                mv.LoadThis();
                mv.LoadArgs();
                mv.InvokeSuperOfCurrentMethod();

                mv.PutThisField(f_cascadeLoadMode, delegate(IMethodVisitor mg)
                {
                    mg.PushEnum(CascadeLoadMode.DEFAULT);
                });
                mv.ReturnValue();
                mv.EndMethod();
            }
        }
        public void constructor_instance_picks_up_InstanceAttributes()
        {
            var instance = new ConstructorInstance(typeof(ClassWithInstanceAttributes));

            instance.Name.ShouldBe("Steve Bono"); // hey, he had a couple good years for awhile
            instance.Interceptors.Single()
            .ShouldBeOfType <ActivatorInterceptor <ClassWithInstanceAttributes> >();
        }
Exemple #10
0
        public void get_and_set_for_a_date_time()
        {
            ConstructorInstance instance = ConstructorInstance.For <ClassWithDate>();

            instance.SetValue("date", "12/23/2009");

            instance.Get("date", typeof(DateTime), new StubBuildSession()).ShouldEqual(new DateTime(2009, 12, 23));
        }
Exemple #11
0
        public void set_and_get_an_integer()
        {
            ConstructorInstance instance = ConstructorInstance.For <ClassWithInt>();

            instance.SetValue("age", "45");

            instance.Get("age", typeof(int), new StubBuildSession()).ShouldEqual(45);
        }
Exemple #12
0
            public ConstructorInstance Use(Type concreteType)
            {
                var instance = new ConstructorInstance(_serviceType, concreteType, ServiceLifetime.Transient);

                _parent.Add(instance);

                return(instance);
            }
Exemple #13
0
        public void name_for_closed_generic_type_that_is_only_one()
        {
            var instance = ConstructorInstance.For <Service <IWidget> >();

            instance.IsOnlyOneOfServiceType = true;

            instance.DefaultArgName().ShouldBe("service_of_IWidget");
        }
Exemple #14
0
        public void name_when_unique()
        {
            var instance = ConstructorInstance.For <AWidget>();

            instance.IsOnlyOneOfServiceType = true;

            instance.DefaultArgName().ShouldBe("aWidget");
        }
        public void has_simple_argument()
        {
            var graph = ServiceGraph.For(x => x.AddTransient <IWidget, AWidget>());

            var ctor = ConstructorInstance.For <WithSimples>().DetermineConstructor(graph, out var message);

            message.ShouldContain("* int number is a 'simple' type that cannot be auto-filled");
        }
Exemple #16
0
        private Instance CreateConstructorInstance(Type messageHandlerType)
        {
            var inst = new ConstructorInstance(messageHandlerType);

            inst.Dependencies.Add <IBus>(new LambdaInstance <IBus>("Dispatch IBus", () => _dispatchBus));
            inst.Dependencies.Add <MessageContext>(new LambdaInstance <MessageContext>("Dispatch MessageContext", () => _dispatchBus.MessageContext));
            return(inst);
        }
Exemple #17
0
        public void create_variable_should_be_through_constructor(Type concreteType, ServiceLifetime lifetime, BuildMode build, DisposeTracking disposal)
        {
            var instance = new ConstructorInstance(concreteType, concreteType, lifetime);

            instance.CreateVariable(build, new ResolverVariables(), false).Creator
            .ShouldBeOfType <ConstructorFrame>()
            .Disposal.ShouldBe(disposal);
        }
Exemple #18
0
        public ServiceFamily Build(Type type, ServiceGraph serviceGraph)
        {
            if (type != typeof(IFancy))
            {
                return(null);
            }

            return(new ServiceFamily(type, new IDecoratorPolicy[0], ConstructorInstance.For <IFancy, Very>()));
        }
Exemple #19
0
        public void the_last_instance_is_the_default()
        {
            var family = new ServiceFamily(typeof(IWidget), new IDecoratorPolicy[0], new Instance[] {
                ConstructorInstance.For <IWidget, AWidget>(),
                ConstructorInstance.For <IWidget, ColorWidget>(),
            });

            family.Default.As <ConstructorInstance>().ImplementationType.ShouldBe(typeof(ColorWidget));
        }
        public void constructor_instance_picks_up_InstanceAttributes()
        {
            var instance = new ConstructorInstance(typeof (ClassWithInstanceAttributes));


            instance.Name.ShouldBe("Steve Bono"); // hey, he had a couple good years for awhile
            instance.Interceptors.Single()
                .ShouldBeOfType<ActivatorInterceptor<ClassWithInstanceAttributes>>();
        }
Exemple #21
0
        public Wrapper(Type behaviorType)
        {
            if (!behaviorType.CanBeCastTo <IActionBehavior>())
            {
                throw new ArgumentOutOfRangeException("behaviorType", "Only types that can be cast to IActionBehavior may be used here");
            }

            _instance = new ConstructorInstance(behaviorType);
        }
        public void to_dependency_source()
        {
            var instance = ConstructorInstance.For <StubbedGateway>();
            var source   = instance.ToDependencySource(typeof(IGateway))
                           .ShouldBeOfType <LifecycleDependencySource>();

            source.Instance.ShouldBe(instance);
            source.PluginType.ShouldBe(typeof(IGateway));
        }
Exemple #23
0
        public void set_and_get_a_string()
        {
            ConstructorInstance instance = ConstructorInstance.For <ColorWidget>();

            instance.SetValue("color", "Red");


            instance.Get("color", typeof(string), new StubBuildSession()).ShouldEqual("Red");
        }
Exemple #24
0
        public void get_and_set_for_a_guid()
        {
            ConstructorInstance instance = ConstructorInstance.For <ClassWithGuid>();
            Guid guid = Guid.NewGuid();

            instance.SetValue("guid", guid.ToString());

            instance.Get("guid", typeof(Guid), new StubBuildSession()).ShouldEqual(guid);
        }
        public void has_unknown_dependency()
        {
            var graph = ServiceGraph.For(x => x.AddTransient <IWidget, AWidget>());

            var ctor = ConstructorInstance.For <WithHitsAndMisses>().DetermineConstructor(graph, out var message);

            message.ShouldContain("* int number is a 'simple' type that cannot be auto-filled");
            message.ShouldContain(
                "* Rule is not registered within this container and cannot be auto discovered by any missing family policy");
        }
Exemple #26
0
        public void get_and_set_a_non_primitive_type_that_is_not_enumerable()
        {
            ConstructorInstance instance = ConstructorInstance.For <ClassWithNonPrimitive>();

            var widget = new AWidget();

            instance.SetValue("widget", widget);

            instance.Get("widget", typeof(IWidget), new StubBuildSession()).ShouldEqual(widget);
        }
Exemple #27
0
 public virtual void NewInstance(ConstructorInstance constructor, Script argumentsScript)
 {
     gen.Emit(OpCodes.Newobj, constructor.Owner.Type);
     Dup();
     if (argumentsScript != null)
     {
         argumentsScript.Invoke(this);
     }
     InvokeConstructor(constructor);
 }
Exemple #28
0
        public ServiceFamily Build(Type type, ServiceGraph serviceGraph)
        {
            if (type.IsConcrete() && matches(type))
            {
                var instance = new ConstructorInstance(type, type, ServiceLifetime.Scoped);
                return(new ServiceFamily(type, new IDecoratorPolicy[0], instance));
            }

            return(null);
        }
Exemple #29
0
            public ConstructorInstance <TConcrete> Use <TConcrete>() where TConcrete : class, T
            {
                var instance = ConstructorInstance.For <T, TConcrete>();

                instance.Lifetime = _lifetime;

                _parent.Add(instance);

                return(instance);
            }
Exemple #30
0
        public void BuildUp(object target)
        {
            var objectType          = target.GetType();
            var constructorInstance = new ConstructorInstance(objectType, objectType, ServiceLifetime.Transient);
            var setters             = constructorInstance.FindSetters(ServiceGraph);

            foreach (var setter in setters)
            {
                setter.ApplyQuickBuildProperties(target, this);
            }
        }
        public void set_and_get_a_nullable_integer()
        {
            ConstructorInstance instance = ConstructorInstance.For <ClassWithNullableInt>();

            instance.As <IConfiguredInstance>().SetValue("age", "45");

            instance.Get("age", typeof(int?), new StubBuildSession()).ShouldEqual(45);

            instance.As <IConfiguredInstance>().SetValue("age", null);
            instance.Get("age", typeof(int?), new StubBuildSession()).ShouldBeNull();
        }
        public void Process(Type type, Registry registry)
        {
            //if (!typeof(IPersistenceDetails).IsAssignableFrom(type))
            //    return;
            if (!type.Name.Equals("PersistenceDetails"))
                return;

            IConfiguredInstance ctor = new ConstructorInstance(type);
            ctor.SetValue("location", this.connectionString);
            registry.For(type.BaseType).HttpContextScoped().Add(ctor);
        }
        public void Process(Type type, Registry registry)
        {
            if (!type.Name.StartsWith("Sql"))
            {
                return;
            }
            if (type == typeof(SqlCurrency))
            {
                return;
            }

            IConfiguredInstance ctor = new ConstructorInstance(type);
            ctor.SetValue("connString", this.connectionString);
            registry.For(type.BaseType).HttpContextScoped().Add(ctor);
        }
        public void try_the_exception_message()
        {
            var instance = new ConstructorInstance(typeof (GuyWithPrimitives));
            instance.Dependencies.Add("name", "Jeremy");

            var ex =
                Exception<StructureMapBuildPlanException>.ShouldBeThrownBy(
                    () => { instance.ToBuilder(typeof (GuyWithPrimitives), new Policies()); });

            ex.ToString()
                .ShouldContain(
                    "Unable to create a build plan for concrete type StructureMap.Testing.Building.GuyWithPrimitives");

            Debug.WriteLine(ex);
        }
        public void ForMemento(InstanceMemento memento, Action<Registry, Instance> callback)
        {
            ForType(memento.PluggedType, concreteType =>
            {
                // TODO -- gotta catch errors here

                _log.Try(() =>
                {
                    var instance = new ConstructorInstance(concreteType);
                    instance.Name = memento.InstanceKey;

                    // TEMPORARY
                    Plugin plugin = PluginCache.GetPlugin(concreteType);
                    var reader = new InstanceMementoPropertyReader(instance, memento, this);
                    plugin.VisitArguments(reader);

                    callback(_registry, instance);
                }).AndLogAnyErrors();
            });
        }
 private static Instance CreateConstructorInstance(Type messageHandlerType)
 {
     var inst = new ConstructorInstance(messageHandlerType);
     inst.Dependencies.Add<IBus>(new LambdaInstance<IBus>("Dispatch IBus", () => _dispatchBus));
     inst.Dependencies.Add<MessageContext>(new LambdaInstance<MessageContext>("Dispatch MessageContext", () => _dispatchBus.MessageContext));
     return inst;
 }
 public InstanceMementoPropertyReader(ConstructorInstance instance, InstanceMemento memento, XmlInstanceReader reader)
 {
     _instance = instance;
     _memento = memento;
     _reader = reader;
 }
        public void SetSetsOnDecoratedCache()
        {
            // Fixture setup
            var anonymousType = typeof(object);
            var anonymousInstance = new ConstructorInstance(anonymousType);
            var anonymousValue = new object();

            var dummyLease = new Mock<ILease>().Object;
            var cacheMock = new Mock<IObjectCache>();

            var sut = new LeasedObjectCache(dummyLease, cacheMock.Object);
            // Exercise system
            sut.Set(anonymousType, anonymousInstance, anonymousValue);
            // Verify outcome
            cacheMock.Verify(c => c.Set(anonymousType, anonymousInstance, anonymousValue));
            // Teardown
        }
 public override void Alter(ConstructorInstance instance)
 {
     instance.Name = _name;
 }
Exemple #40
0
        /// <summary>
        /// Adds a new Instance for the concreteType with a name
        /// </summary>
        /// <param name="concreteType"></param>
        /// <param name="name"></param>
        public void AddType(Type concreteType, string name)
        {
            if (!concreteType.CanBeCastTo(_pluginType)) return;

            if (!hasType(concreteType) && Policies.CanBeAutoFilled(concreteType))
            {
                var instance = new ConstructorInstance(concreteType);
                if (name.IsNotEmpty()) instance.Name = name;
                AddInstance(instance);
            }
        }
        public void HasClearsCacheAppropriately(bool isExpired, int clearCount)
        {
            // Fixture setup
            var leaseStub = new Mock<ILease>();
            leaseStub.SetupGet(l => l.IsExpired).Returns(isExpired);

            var cacheMock = new Mock<IObjectCache>();

            var sut = new LeasedObjectCache(leaseStub.Object, cacheMock.Object);
            // Exercise system
            var dummyType = typeof(object);
            var dummyInstance = new ConstructorInstance(dummyType);
            sut.Has(dummyType, dummyInstance);
            // Verify outcome
            cacheMock.Verify(c => c.DisposeAndClear(), Times.Exactly(clearCount));
            // Teardown
        }
        public void SetRenewsLease()
        {
            // Fixture setup
            var leaseMock = new Mock<ILease>();
            var dummyCache = new Mock<IObjectCache>().Object;

            var sut = new LeasedObjectCache(leaseMock.Object, dummyCache);
            // Exercise system
            var anonymousType = typeof(object);
            var anonymousInstance = new ConstructorInstance(anonymousType);
            var anonymousValue = new object();
            sut.Set(anonymousType, anonymousInstance, anonymousValue);
            // Verify outcome
            leaseMock.Verify(l => l.Renew());
            // Teardown
        }
 public abstract void Alter(ConstructorInstance instance);
 public override void Alter(ConstructorInstance instance)
 {
 }
Exemple #45
0
        public ConstructorInstance ToInstance(IPluginFactory factory, Type pluginType)
        {
            var plugin = factory.PluginFor(PluggedType());

            var instance = new ConstructorInstance(plugin);
            if (InstanceKey.IsNotEmpty())
            {
                instance.Name = InstanceKey;
            }

            var reader = new InstanceMementoPropertyReader(instance, this, factory);
            plugin.VisitArguments(reader);

            return instance;
        }
Exemple #46
0
        private Instance determineDefault()
        {
            if (_instances.Count == 1)
            {
                return _instances.Single();
            }

            // ONLY decide on a default Instance if there is none
            if (_instances.Count == 0 && _pluginType.IsConcrete())
            {
                var instance = new ConstructorInstance(_pluginType);
                AddInstance(instance);

                return instance;
            }

            return null;
        }
        public void HasReturnsCorrectResult(bool expected)
        {
            // Fixture setup
            var dummyLease = new Mock<ILease>().Object;

            var anonymousType = typeof(object);
            var anonymousInstance = new ConstructorInstance(anonymousType);
            var cacheStub = new Mock<IObjectCache>();
            cacheStub.Setup(c => c.Has(anonymousType, anonymousInstance)).Returns(expected);

            var sut = new LeasedObjectCache(dummyLease, cacheStub.Object);
            // Exercise system
            var result = sut.Has(anonymousType, anonymousInstance);
            // Verify outcome
            Assert.Equal(expected, result);
            // Teardown
        }