/// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public void Execute(ObjectConstructionArgs args)
        {
            if (args.Result != null)
                return;

            var type = args.Configuration.Type;

            if(type.IsInterface)
            {
                return;
            }

            if(args.AbstractTypeCreationContext.IsLazy)
            {
                //here we create a lazy loaded version of the class
                args.Result = CreateLazyObject(args);
                args.AbortPipeline();

            }
            else
            {
                //here we create a concrete version of the class
                args.Result = CreateObject(args);
                args.AbortPipeline();

                
            }
        }
          /// <summary>
        /// Initializes a new instance of the <see cref="MultiInterfacePropertyInterceptor"/> class.
        /// </summary>
        /// <param name="args">The args.</param>
        public MultiInterfacePropertyInterceptor(ObjectConstructionArgs args)
        {
            _args = args;
              _configs =
                  new[] {args.Configuration}.Union(args.Parameters[CreateMultiInferaceTask.MultiInterfaceConfigsKey] as IEnumerable<AbstractTypeConfiguration>);
			  _lazyValues = new Lazy<IDictionary<string, object>>(LoadValues);
        }
 public override void Execute(ObjectConstructionArgs args)
 {
     using (new DepthCheck(args.Configuration.Type))
     {
         base.Execute(args);
     }
 }
        /// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public override void Execute(ObjectConstructionArgs args)
        {
            if (args.Result == null
                && args.Configuration != null
                && !args.Configuration.Type.IsInterface
                && !args.Configuration.Type.IsSealed)
            {
                if(args.AbstractTypeCreationContext.IsLazy && DisableLazyLoading.Current == LazyLoadSetting.Enabled)
                {
                    //here we create a lazy loaded version of the class
                    args.Result = CreateLazyObject(args);
                    args.Counters.ProxyModelsCreated++;

                }
                else
                {
                    //here we create a concrete version of the class
                    args.Result = CreateObject(args);
                    args.Counters.ModelsMapped++;
                    args.Counters.ConcreteModelCreated++;
                }
            }

            base.Execute(args);
        }
 public LazyObjectInterceptor(Action<object> mappingAction, ObjectConstructionArgs args)
 {
     MappingAction = (obj) =>
     {
         args.Counters.ProxyModelsCreated++;
         mappingAction(obj);
     };
 }
 /// <summary>
 /// Executes the specified args.
 /// </summary>
 /// <param name="args">The args.</param>
 public void Execute(ObjectConstructionArgs args)
 {
     if (args.Result== null 
         && args.Configuration.Type.IsInterface) 
     {
         args.Result = _generator.CreateInterfaceProxyWithoutTarget(args.Configuration.Type, new InterfacePropertyInterceptor(args));
     }
 }
        public override void Execute(ObjectConstructionArgs args)
        {
            
                var counter = GetCounter();
                counter++;
            ThreadData.SetValue(CalledKey,counter);

            base.Execute(args);
        }
        public void Execute(ObjectConstructionArgs args)
        {
            if (args.Result != null && args.Configuration.Cachable && args.AbstractTypeCreationContext.CacheEnabled && DisableCache.Current == CacheSetting.Enabled)
            {
                var key = args.Context.Name + args.AbstractTypeCreationContext.GetUniqueKey();

                // This will also OVERRIDE any existing item that may already be cached (to be consistent across different cache impls)
                // Will allow for multiple threads to update the cached object on first load, when they are all racing to cache the item for the first time
                _cacheManager.AddOrUpdate(key, args.Result);
            }
        }
        /// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public override void Execute(ObjectConstructionArgs args)
        {
            if (args.Result== null 
                && args.Configuration.Type.IsInterface) 
            {
                args.Result = _generator.CreateInterfaceProxyWithoutTarget(args.Configuration.Type, new InterfacePropertyInterceptor(args));
                args.Counters.ProxyModelsCreated++;
            }

            base.Execute(args);
        }
        /// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public void Execute(ObjectConstructionArgs args)
        {
            if (args.Result != null)
                return;

            if (args.Configuration.Type.IsInterface) 
            {
                
                args.Result = _generator.CreateInterfaceProxyWithoutTarget(args.Configuration.Type, new InterfacePropertyInterceptor(args));
                // args.AbortPipeline();
            }
        }
        public override void Execute(ObjectConstructionArgs args)
        {
            var innerCallback = args.CreatedCallback;
            //args.CreatedCallback = () =>
            //{
                var counter = GetCounter();
                counter++;
                ThreadData.SetValue(CacheMissKey, counter);
            //    innerCallback();
            //};

            base.Execute(args);
        }
Exemple #12
0
        public void Execute(ObjectConstructionArgs args)
        {
            if (args.Result == null && args.Configuration.Cachable && args.AbstractTypeCreationContext.CacheEnabled && DisableCache.Current == CacheSetting.Enabled)
            {
                var key = args.Context.Name + args.AbstractTypeCreationContext.GetUniqueKey();

                var cacheItem = _cacheManager.Get<object>(key);
                if (cacheItem != null)
                {
                    args.Result = cacheItem;
                    args.AbortPipeline();
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="InterfacePropertyInterceptor"/> class.
        /// </summary>
        /// <param name="args">The args.</param>
        public InterfacePropertyInterceptor(ObjectConstructionArgs args)
        {
            _args = args;
            _fullName = _args.Configuration.Type.FullName;
            Values = new ConcurrentDictionary<string, object>();

            _mappingContext = _args.Service.CreateDataMappingContext(_args.AbstractTypeCreationContext, null);

            //if lazy loading diabled load all values now
            if (!args.AbstractTypeCreationContext.IsLazy)
            {
                LoadAllValues();
            }
        }
        public void Execute(ObjectConstructionArgs args)
        {
            if (args.Result == null 
                && args.Configuration.Type.IsInterface 
                && args.Parameters.ContainsKey(MultiInterfaceConfigsKey))
            {
                var configs = args.Parameters[MultiInterfaceConfigsKey] as IEnumerable<AbstractTypeConfiguration>;

                if (configs != null)
                {
                    args.Result = _generator.CreateInterfaceProxyWithoutTarget(
                        args.Configuration.Type,
                        configs.Select(x => x.Type).ToArray(),
                        new MultiInterfacePropertyInterceptor(args));
                }
            }
        }
        public override void Execute(ObjectConstructionArgs args)
        {
            if (args.Result == null 
                && args.Configuration.Cachable 
                && DisableCache.Current == CacheSetting.Enabled
                && args.AbstractTypeCreationContext.CacheEnabled
                )
            {
                var key = CacheKeyGenerator.Generate(args);

                var cacheItem = CacheManager.Get<object>(key);
                if (cacheItem != null)
                {
                    args.Result = cacheItem;
                    args.Counters.CachedModels++;
                }

                DisableLazyLoading disableLazyLoading = null;

                if (args.Service.GlassContext.Config.EnableLazyLoadingForCachableModels == false)
                {
                    disableLazyLoading = new DisableLazyLoading();
                }

                try
                {
                    base.Execute(args);
                    CacheManager.AddOrUpdate(key, args.Result);
                }
                finally
                {
                    if (disableLazyLoading != null)
                    {
                        disableLazyLoading.Dispose();
                    }
                }
            }
            else 
            {
                base.Execute(args);
            }


        }
        public void Execute_TypeIsInterface_NoObjectCreated()
        {
            //Assign
            Type    type    = typeof(IStubInterface);
            var     service = Substitute.For <IAbstractService>();
            Context context = Context.Create(Substitute.For <IDependencyResolver>());

            AbstractTypeCreationContext abstractTypeCreationContext = Substitute.For <AbstractTypeCreationContext>();

            abstractTypeCreationContext.RequestedType = type;

            var configuration = Substitute.For <AbstractTypeConfiguration>();

            configuration.Type = type;

            ObjectConstructionArgs args = new ObjectConstructionArgs(context, abstractTypeCreationContext, configuration, service, new ModelCounter());

            //Act
            _task.Execute(args);

            //Assert
            Assert.IsNull(args.Result);
        }
        /// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public void Execute(ObjectConstructionArgs args)
        {
            if (args.Result != null ||
                args.Configuration == null ||
                args.Configuration.Type.IsInterface ||
                args.Configuration.Type.IsSealed)
            {
                return;
            }

            if (args.AbstractTypeCreationContext.IsLazy)
            {
                //here we create a lazy loaded version of the class
                args.Result = CreateLazyObject(args);
                // args.AbortPipeline();
            }
            else
            {
                //here we create a concrete version of the class
                args.Result = CreateObject(args);
                //args.AbortPipeline();
            }
        }
        public override void Execute(ObjectConstructionArgs args)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            try
            {
                base.Execute(args);
            }
            finally
            {
                stopwatch.Stop();
                if (stopwatch.ElapsedMilliseconds > _debugSettings.SlowModelThreshold)
                {

                    var key = _cacheKeyGenerator.Generate(args) + "stopwatch";
                    var finaltType = args.Result.GetType();

                    _log.Warn("Slow Glass Model - Time: {0} Cachable: {1} Type: {2} Key: {3}".Formatted(stopwatch.ElapsedMilliseconds, args.Configuration.Cachable, finaltType.FullName, key));
                }
            }
        }
Exemple #19
0
        public void CanSerializeAndDeserializeGeneratedInterface()
        {
            //Assign
            Type type        = typeof(IStubInterface);
            var  glassConfig = Substitute.For <IGlassConfiguration>();
            var  service     = Substitute.For <IAbstractService>();

            Context context = Context.Create(Substitute.For <IDependencyResolver>());

            AbstractTypeCreationContext abstractTypeCreationContext = Substitute.For <AbstractTypeCreationContext>();

            abstractTypeCreationContext.Options = new GetOptions()
            {
                Type = typeof(IStubInterface)
            };

            var configuration = Substitute.For <AbstractTypeConfiguration>();

            configuration.Type = type;

            ObjectConstructionArgs args = new ObjectConstructionArgs(context, abstractTypeCreationContext, configuration, service);

            //Act
            _task.Execute(args);
            byte[] serialized = Serialize(args.Result);

            /*SerializationInfo info = new SerializationInfo(typeof(IStubInterface),);
             * StreamingContext context = new StreamingContext();
             * ProxyObjectReference pr = new ProxyObjectReference(info, new StreamingContext() )*/
            IStubInterface deserialized = Deserialize <IStubInterface>(serialized);


            //Assert
            Assert.IsNotNull(args.Result);
            Assert.IsTrue(args.Result is IStubInterface);
            Assert.IsFalse(args.Result.GetType() == typeof(IStubInterface));
        }
Exemple #20
0
        public void Execute_RequestInstanceOfClassWithParameters_NoInstanceReturnedDoesntHandle()
        {
            //Assign
            var task = new WindsorConstruction();


            var resolver = DependencyResolver.CreateStandardResolver();

            resolver.Container.Register(
                Component.For <Mapper.Config>().Instance(new Mapper.Config())
                );
            var context = Context.Create(resolver);

            var typeConfig = Substitute.For <AbstractTypeConfiguration>();

            typeConfig.Type = typeof(StubClassWithParameters);

            string param1 = "test param1";
            int    param2 = 450;
            double param3 = 489;
            string param4 = "param4 test";

            var typeCreationContext = Substitute.For <AbstractTypeCreationContext>();

            typeCreationContext.ConstructorParameters = new object[] { param1, param2, param3, param4 };


            var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig, null);

            Assert.IsNull(args.Result);

            //Act
            task.Execute(args);

            //Assert
            Assert.IsNull(args.Result);
        }
Exemple #21
0
        /// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public override void Execute(ObjectConstructionArgs args)
        {
            if (args.Result == null &&
                args.Configuration != null &&
                !args.Configuration.Type.IsInterface &&
                !args.Configuration.Type.IsSealed)
            {
                if (_lazyLoadingHelper.IsEnabled(args.Options))
                {
                    //here we create a lazy loaded version of the class
                    args.Result = CreateLazyObject(args);
                    ModelCounter.Instance.ProxyModelsCreated++;
                }
                else
                {
                    //here we create a concrete version of the class
                    args.Result = CreateObjectAndMapProperties(args);
                    ModelCounter.Instance.ModelsMapped++;
                    ModelCounter.Instance.ConcreteModelCreated++;
                }
            }

            base.Execute(args);
        }
        /// <summary>
        /// Creates the object.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <returns>System.Object.</returns>
        protected virtual object CreateObject(ObjectConstructionArgs args)
        {
            var constructorParameters = args.AbstractTypeCreationContext.ConstructorParameters;

            Delegate conMethod = null;
            object   obj;

            if (constructorParameters == null || constructorParameters.Length == 0)
            {
                //conMethod = args.Configuration.DefaultConstructor;
                obj = Activator.CreateInstance(args.Configuration.Type);
            }
            else
            {
                var parameters      = constructorParameters.Select(x => x.GetType()).ToArray();
                var constructorInfo = args.Configuration.Type.GetConstructor(parameters);
                conMethod = args.Configuration.ConstructorMethods[constructorInfo];
                obj       = conMethod.DynamicInvoke(constructorParameters);
            }

            args.Configuration.MapPropertiesToObject(obj, args.Service, args.AbstractTypeCreationContext);

            return(obj);
        }
Exemple #23
0
        public void Execute_EnforeTemplateOnlyInheritsTemplate_NextCalled()
        {
            //Arrange
            var  task       = new EnforcedTemplateCheck();
            bool nextCalled = false;

            task.SetNext(x => nextCalled = true);


            using (Db database = new Db
            {
                new DbTemplate(new ID(TemplateInferredTypeTaskFixture.StubInferred.TemplateId)),
                new Sitecore.FakeDb.DbItem("Target", ID.NewID,
                                           new ID(TemplateInferredTypeTaskFixture.StubInferred.TemplateId))
            })
            {
                var path = "/sitecore/content/Target";
                var item = database.GetItem(path);

                var config = new SitecoreTypeConfiguration();
                config.EnforceTemplate = SitecoreEnforceTemplate.Template;
                config.TemplateId      = item.TemplateID;

                var typeContext = new SitecoreTypeCreationContext();
                typeContext.Item = item;

                var args = new ObjectConstructionArgs(null, typeContext, config, null);

                //Act
                task.Execute(args);

                //Assert
                Assert.IsNull(args.Result);
                Assert.IsTrue(nextCalled);
            }
        }
        /// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public override void Execute(ObjectConstructionArgs args)
        {
            if (args.Result == null &&
                args.Configuration != null &&
                !args.Configuration.Type.IsInterface &&
                !args.Configuration.Type.IsSealed)
            {
                if (args.AbstractTypeCreationContext.IsLazy && DisableLazyLoading.Current == LazyLoadSetting.Enabled)
                {
                    //here we create a lazy loaded version of the class
                    args.Result = CreateLazyObject(args);
                    args.Counters.ProxyModelsCreated++;
                }
                else
                {
                    //here we create a concrete version of the class
                    args.Result = CreateObject(args);
                    args.Counters.ModelsMapped++;
                    args.Counters.ConcreteModelCreated++;
                }
            }

            base.Execute(args);
        }
Exemple #25
0
        public void Execute_ArgsNotNullMultipleInterface_ReturnsMultiInterfaceProxy()
        {
            //Arrange

            var config1 = new StubAbstractTypeConfiguration();
            var config2 = new StubAbstractTypeConfiguration();

            config1.Type = typeof(IStubTarget);
            config2.Type = typeof(IStubTarget2);

            //  var args = new ObjectConstructionArgs(null, null, new[] { config1, config2 }, null);
            var args = new ObjectConstructionArgs(null, null, config1, null, new ModelCounter());

            args.Parameters[CreateMultiInferaceTask.MultiInterfaceConfigsKey] = new[] { config2 };
            var task = new CreateMultiInferaceTask();

            //Act
            task.Execute(args);

            //Assert
            Assert.IsNotNull(args.Result);
            Assert.IsTrue(args.Result is IStubTarget);
            Assert.IsTrue(args.Result is IStubTarget2);
        }
Exemple #26
0
        public void Execute_RequestInstanceOfClassWithService_ReturnsInstanceWithService()
        {
            //Assign
            var task = new WindsorConstruction();

            var resolver = DependencyResolver.CreateStandardResolver() as DependencyResolver;
            var context  = Context.Create(resolver);
            var service  = Substitute.For <AbstractService>();

            resolver.Container.Register(
                Component.For <StubServiceInterface>().ImplementedBy <StubService>().LifestyleTransient()
                );

            var typeConfig = Substitute.For <AbstractTypeConfiguration>();

            typeConfig.Type = typeof(StubClassWithService);

            var typeCreationContext = Substitute.For <AbstractTypeCreationContext>();


            var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig, service);

            Assert.IsNull(args.Result);

            //Act
            task.Execute(args);

            //Assert
            Assert.IsNotNull(args.Result);
            Assert.IsTrue(args.Result is StubClassWithService);

            var stub = args.Result as StubClassWithService;

            Assert.IsNotNull(stub.Service);
            Assert.IsTrue(stub.Service is StubService);
        }
Exemple #27
0
        public void Execute_RequestInstanceOfClass_ReturnsInstance()
        {
            //Assign
            var task = new WindsorConstruction();

            var context    = Context.Create(DependencyResolver.CreateStandardResolver());
            var typeConfig = Substitute.For <AbstractTypeConfiguration>();

            typeConfig.Type = typeof(StubClass);

            var typeCreationContext = Substitute.For <AbstractTypeCreationContext>();
            var service             = Substitute.For <AbstractService>();

            var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig, service);

            Assert.IsNull(args.Result);

            //Act
            task.Execute(args);

            //Assert
            Assert.IsNotNull(args.Result);
            Assert.IsTrue(args.Result is StubClass);
        }
Exemple #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MultiInterfacePropertyInterceptor"/> class.
 /// </summary>
 /// <param name="args">The args.</param>
 public MultiInterfacePropertyInterceptor(ObjectConstructionArgs args)
 {
     _args    = args;
     _configs =
         new[] { args.Configuration }.Union(args.Parameters[CreateMultiInferaceTask.MultiInterfaceConfigsKey] as IEnumerable <AbstractTypeConfiguration>);
 }
 /// <summary>
 /// Creates the lazy object.
 /// </summary>
 /// <param name="args">The args.</param>
 /// <returns>System.Object.</returns>
 protected virtual object CreateLazyObject(ObjectConstructionArgs args)
 {
     return  _generator.CreateClassProxy(args.Configuration.Type, new LazyObjectInterceptor(args));
 }
 public virtual string GetCacheName(ObjectConstructionArgs args)
 {
     return("Default");
 }
 public SearchInterceptor(ObjectConstructionArgs args)
 {
     IndexFields = new string[] {};
     _args       = args;
     _values     = new Dictionary <string, object>();
 }
 public override void Execute(ObjectConstructionArgs args)
 {
     base.Next(args);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="InterfacePropertyInterceptor"/> class.
 /// </summary>
 /// <param name="args">The args.</param>
 public InterfacePropertyInterceptor(ObjectConstructionArgs args)
 {
     _args       = args;
     _lazyValues = new Lazy <IDictionary <string, object> >(LoadValues);
 }
Exemple #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InterfacePropertyInterceptor"/> class.
 /// </summary>
 /// <param name="args">The args.</param>
 public InterfacePropertyInterceptor(ObjectConstructionArgs args)
 {
     _args       = args;
     _fullName   = _args.Configuration.Type.FullName;
     _lazyValues = new Lazy <IDictionary <string, object> >(LoadValues);
 }
        /// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public void Execute(ObjectConstructionArgs args)
        {
            if (args.Result != null)
            {
                return;
            }
            var resolver = args.Context.DependencyResolver as DependencyResolver;

            if (resolver == null)
            {
                return;
            }

            if (args.AbstractTypeCreationContext.ConstructorParameters != null &&
                args.AbstractTypeCreationContext.ConstructorParameters.Any())
            {
                return;
            }
            if (args.Configuration == null)
            {
                return;
            }

            var configuration = args.Configuration;
            var type          = configuration.Type;
            var container     = resolver.Container;

            if (!type.IsClass)
            {
                return;
            }

            TypeRegistrationCheck(container, type);

            Action <object> mappingAction = (target) =>
                                            configuration.MapPropertiesToObject(target, args.Service,
                                                                                args
                                                                                .AbstractTypeCreationContext);


            object result;

            if (args.AbstractTypeCreationContext.IsLazy)
            {
                using (new UsingLazyInterceptor())
                {
                    result = container.Resolve(type.FullName + "lazy", type);
                    var proxy       = result as IProxyTargetAccessor;
                    var interceptor =
                        proxy.GetInterceptors().First(x => x is LazyObjectInterceptor) as
                        LazyObjectInterceptor;
                    interceptor.MappingAction = mappingAction;
                    interceptor.Actual        = result;
                }
            }
            else
            {
                result = container.Resolve(type);
                if (result != null)
                {
                    mappingAction(result);
                }
            }

            args.Result = result;
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="InterfacePropertyInterceptor"/> class.
		/// </summary>
		/// <param name="args">The args.</param>
		public InterfacePropertyInterceptor(ObjectConstructionArgs args)
		{
			_args = args;
			_lazyValues = new Lazy<IDictionary<string, object>>(LoadValues);
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="LazyObjectInterceptor"/> class.
 /// </summary>
 /// <param name="args">The args.</param>
 public LazyObjectInterceptor(ObjectConstructionArgs args)
 {
     _args = args;
 }
        public void Intercept_InterceptsMultiplePropertiesOnDifferentInterfaces_SetsExpectedPropertyValues()
        {
            //Arrange
            var service = Substitute.For <IAbstractService>();
            var config1 = new StubAbstractTypeConfiguration();
            var config2 = new StubAbstractTypeConfiguration();

            var property1 = new StubAbstractPropertyConfiguration();
            var property2 = new StubAbstractPropertyConfiguration();

            var mapper1 = new StubAbstractDataMapper();
            var mapper2 = new StubAbstractDataMapper();

            var expected1 = "test random 1";
            var expected2 = "some other random";

            var propertyName1 = "Property1";
            var propertyName2 = "Property2";


            var info1 = new FakePropertyInfo(typeof(string), propertyName1, typeof(IStubTarget));
            var info2 = new FakePropertyInfo(typeof(string), propertyName2, typeof(IStubTarget2));

            config1.AddProperty(property1);
            config2.AddProperty(property2);

            property1.Mapper       = mapper1;
            property2.Mapper       = mapper2;
            property1.PropertyInfo = info1;
            property2.PropertyInfo = info2;

            var args = new ObjectConstructionArgs(null, null, config1, service, new ModelCounter());

            args.Parameters = new Dictionary <string, object>();
            args.Parameters[CreateMultiInferaceTask.MultiInterfaceConfigsKey] = new[] { config2 };
            var interceptor = new MultiInterfacePropertyInterceptor(args);


            var setInvocation1 = Substitute.For <IInvocation>();
            var setInvocation2 = Substitute.For <IInvocation>();

            setInvocation1.Arguments.Returns(new[] { expected1 });
            setInvocation2.Arguments.Returns(new[] { expected2 });

            setInvocation1.Method.Returns(typeof(IStubTarget).GetProperty(propertyName1).GetSetMethod());
            setInvocation2.Method.Returns(typeof(IStubTarget2).GetProperty(propertyName2).GetSetMethod());


            //Act

            interceptor.Intercept(setInvocation1);
            interceptor.Intercept(setInvocation2);

            //Assert

            var getInvocation1 = Substitute.For <IInvocation>();
            var getInvocation2 = Substitute.For <IInvocation>();

            getInvocation1.Method.Returns(typeof(IStubTarget).GetProperty(propertyName1).GetGetMethod());
            getInvocation2.Method.Returns(typeof(IStubTarget2).GetProperty(propertyName2).GetGetMethod());



            interceptor.Intercept(getInvocation1);
            interceptor.Intercept(getInvocation2);


            Assert.AreEqual(expected1, getInvocation1.ReturnValue);
            Assert.AreEqual(expected2, getInvocation2.ReturnValue);
        }
Exemple #39
0
 public SearchInterceptor(ObjectConstructionArgs args)
 {
     _args = args;
 }
Exemple #40
0
        /// <summary>
        /// Executes the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        public void Execute(ObjectConstructionArgs args)
        {
            if (args.Result != null)
            {
                return;
            }
            var resolver = args.Context.DependencyResolver as DependencyResolver;

            if (resolver == null)
            {
                return;
            }

            if (args.AbstractTypeCreationContext.ConstructorParameters == null ||
                !args.AbstractTypeCreationContext.ConstructorParameters.Any())
            {
                var type      = args.Configuration.Type;
                var container = resolver.Container;

                if (type.IsClass)
                {
                    if (!container.Kernel.HasComponent(typeof(LazyObjectInterceptor)))
                    {
                        container.Kernel.Register(Component.For <LazyObjectInterceptor>().LifestyleTransient());
                    }
                    if (!container.Kernel.HasComponent(type))
                    {
                        container.Kernel.Register(
                            Component.For(type).Named(type.FullName).LifeStyle.Is(LifestyleType.Transient)
                            );
                        container.Kernel.Register(
                            Component.For(type).Named(type.FullName + "lazy").LifeStyle.Is(LifestyleType.Transient)
                            .Interceptors <LazyObjectInterceptor>()
                            );
                    }

                    Action <object> mappingAction = (target) =>
                                                    args.Configuration.MapPropertiesToObject(target, args.Service, args.AbstractTypeCreationContext);


                    object result = null;
                    if (args.AbstractTypeCreationContext.IsLazy)
                    {
                        using (new UsingLazyInterceptor())
                        {
                            result = container.Resolve(type.FullName + "lazy", type);
                            var proxy       = result as IProxyTargetAccessor;
                            var interceptor = proxy.GetInterceptors().First(x => x is LazyObjectInterceptor) as LazyObjectInterceptor;
                            interceptor.MappingAction = mappingAction;
                            interceptor.Actual        = result;
                        }
                    }
                    else
                    {
                        result = container.Resolve(type);
                        if (result != null)
                        {
                            mappingAction(result);
                        }
                    }



                    args.Result = result;
                }//if (type.IsClass)
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LazyObjectInterceptor"/> class.
 /// </summary>
 /// <param name="args">The args.</param>
 public LazyObjectInterceptor(ObjectConstructionArgs args)
 {
     _args = args;
 }
   /// <summary>
 /// Initializes a new instance of the <see cref="MultiInterfacePropertyInterceptor"/> class.
 /// </summary>
 /// <param name="args">The args.</param>
 public MultiInterfacePropertyInterceptor(ObjectConstructionArgs args)
 {
     _args = args;
       _configs =
           new[] {args.Configuration}.Union(args.Parameters[CreateMultiInferaceTask.MultiInterfaceConfigsKey] as IEnumerable<AbstractTypeConfiguration>);
 }
        /// <summary>
        /// Creates the object.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <returns>System.Object.</returns>
        protected virtual object CreateObject(ObjectConstructionArgs args)
        {

            var constructorParameters = args.AbstractTypeCreationContext.ConstructorParameters;

            Delegate conMethod = null;
            object obj;

            try
            {
                if (constructorParameters == null || constructorParameters.Length == 0)
                {
                    //conMethod = args.Configuration.DefaultConstructor;
                    obj = Activator.CreateInstance(args.Configuration.Type);
                }
                else
                {
                    var parameters = constructorParameters.Select(x => x.GetType()).ToArray();
                    var constructorInfo = args.Configuration.Type.GetConstructor(parameters);
                    conMethod = args.Configuration.ConstructorMethods[constructorInfo];
                    obj = conMethod.DynamicInvoke(constructorParameters);
                }

                args.Configuration.MapPropertiesToObject(obj, args.Service, args.AbstractTypeCreationContext);
            }
            catch (Exception ex)
            {
                throw new MapperException("Failed to create type {0}".Formatted(args.Configuration.Type), ex);
            }
            return obj;
        }
		private IDictionary<string, object> LoadValues()
		{
			var config = _args.Configuration;

			var values = new Dictionary<string, object>();
			var mappingContext = _args.Service.CreateDataMappingContext(_args.AbstractTypeCreationContext, null);

			foreach (var property in config.Properties)
			{
				var result = property.Mapper.MapToProperty(mappingContext);
				values[property.PropertyInfo.Name] = result;
			}

            //release the context
		    _args = null;

			return values;
		}
Exemple #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InterfacePropertyInterceptor"/> class.
 /// </summary>
 /// <param name="args">The args.</param>
 public InterfacePropertyInterceptor(ObjectConstructionArgs args)
 {
     _args = args;
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="InterfacePropertyInterceptor"/> class.
		/// </summary>
		/// <param name="args">The args.</param>
		public InterfacePropertyInterceptor(ObjectConstructionArgs args)
		{
			_args = args;
		    _fullName = _args.Configuration.Type.FullName;
			_lazyValues = new Lazy<IDictionary<string, object>>(LoadValues);
		}
 public override void Execute(ObjectConstructionArgs args)
 {
     WasCalled = true;
 }
 /// <summary>
 /// Creates the lazy object.
 /// </summary>
 /// <param name="args">The args.</param>
 /// <returns>System.Object.</returns>
 protected virtual object CreateLazyObject(ObjectConstructionArgs args)
 {
     return(_generator.CreateClassProxy(args.Configuration.Type, new LazyObjectInterceptor(args)));
 }
        /// <summary>
        /// Creates the object.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <returns>System.Object.</returns>
        protected virtual object CreateObject(ObjectConstructionArgs args)
        {

            var constructorParameters = args.AbstractTypeCreationContext.ConstructorParameters;

            var parameters =
                constructorParameters == null || !constructorParameters.Any()
                    ? Type.EmptyTypes
                    : constructorParameters.Select(x => x.GetType()).ToArray();

            var constructorInfo = args.Configuration.Type.GetConstructor(parameters);

            Delegate conMethod = args.Configuration.ConstructorMethods[constructorInfo];

            var obj = conMethod.DynamicInvoke(constructorParameters);

            args.Configuration.MapPropertiesToObject(obj, args.Service, args.AbstractTypeCreationContext);

            return obj;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="InterfacePropertyInterceptor"/> class.
 /// </summary>
 /// <param name="args">The args.</param>
 public InterfacePropertyInterceptor(ObjectConstructionArgs args)
 {
     _args = args;
 }