示例#1
0
        private void initialize(SharpSerializerXmlSettings settings)
        {
            this.InstanceCreator = settings.InstanceCreator ?? new DefaultInstanceCreator();

            // PropertiesToIgnore
            PropertyProvider.PropertiesToIgnore = settings.AdvancedSettings.PropertiesToIgnore;
            PropertyProvider.AttributesToIgnore = settings.AdvancedSettings.AttributesToIgnore;
            //RootName
            RootName = settings.AdvancedSettings.RootName;
            // TypeNameConverter)
            ITypeNameConverter typeNameConverter = settings.AdvancedSettings.TypeNameConverter ??
                                                   DefaultInitializer.GetTypeNameConverter(
                settings.IncludeAssemblyVersionInTypeName,
                settings.IncludeCultureInTypeName,
                settings.IncludePublicKeyTokenInTypeName);
            // SimpleValueConverter
            ISimpleValueConverter simpleValueConverter = settings.AdvancedSettings.SimpleValueConverter ??
                                                         DefaultInitializer.GetSimpleValueConverter(settings.Culture, typeNameConverter);
            // XmlWriterSettings
            XmlWriterSettings xmlWriterSettings = DefaultInitializer.GetXmlWriterSettings(settings.Encoding);
            // XmlReaderSettings
            XmlReaderSettings xmlReaderSettings = DefaultInitializer.GetXmlReaderSettings();

            // Create Serializer and Deserializer
            var reader = new DefaultXmlReader(typeNameConverter, simpleValueConverter, xmlReaderSettings);
            var writer = new DefaultXmlWriter(typeNameConverter, simpleValueConverter, xmlWriterSettings);

            _serializer   = new XmlPropertySerializer(writer);
            _deserializer = new XmlPropertyDeserializer(reader);
        }
        /// <summary>
        /// PerCallInterfaceLifetime constructor
        /// </summary>
        /// <param name="outType">The type of the object to be stored in the current Lifetime container</param>
        /// <param name="createInstanceObj">Instance creator</param>
        public PerCallInterfaceLifetime(Type outType, IInstanceCreator createInstanceObj)
            : base(outType)
        {
            Contract.Requires <ArgumentNullException>(createInstanceObj != null, "createInstanceObj");

            _createInstanceObj = createInstanceObj;
        }
示例#3
0
 public ObjectBuilder(IInstanceCreator creator, ObjectBuilderContext objectBuilderContext, IConverterContextFactory contextFactory)
 {
     this.contextFactory  = contextFactory;
     ObjectBuilderContext = objectBuilderContext;
     this.creator         = creator;
     sourceValueConverter = objectBuilderContext.SourceValueConverter;
 }
示例#4
0
 public object GetInstance(NancyContainer container, IInstanceCreator creator)
 {
     if (creator.Instance == null)
     {
         creator.Instance = creator.CreateInstance(container);
     }
     return creator.Instance;
 }
示例#5
0
        private T ValidateInstCreator <T>(IInstanceCreator instCreator)
        {
            var obj = instCreator.CreateInstance(new TestInjectionResolver());

            Assert.IsNotNull(obj);
            Assert.IsTrue(obj is T);

            return((T)obj);
        }
示例#6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebDriverFactoryCreator"/> class.
        /// </summary>
        /// <param name="instanceCreator">Instance creator.</param>
        public WebDriverFactoryCreator(IInstanceCreator instanceCreator)
        {
            if (instanceCreator == null)
            {
                throw new ArgumentNullException(nameof(instanceCreator));
            }

            this.instanceCreator = instanceCreator;
        }
        public void CreateInstance_returns_exception_for_failing_method( )
        {
            IInstanceCreator creator = InstanceCreator.ForType <FailingClass>( );

            object result = creator.CreateInstance( );

            var actual = Assert.IsType <Exception>(result);

            Assert.Equal(typeof(FailingClass).FullName, actual.Message);
        }
示例#8
0
        /// <summary>
        /// PerCallInterfaceLifetime constructor
        /// </summary>
        /// <param name="outType">The type of the object to be stored in the current Lifetime container</param>
        /// <param name="createInstanceObj">Instance creator</param>
        public PerCallInterfaceLifetime(Type outType, IInstanceCreator createInstanceObj)
            : base(outType)
        {
            if (createInstanceObj == null)
            {
                throw new ArgumentNullException(nameof(createInstanceObj));
            }

            _createInstanceObj = createInstanceObj;
        }
示例#9
0
 public ITypeMapper <TSource, TTarget> CreateWith(Func <TSource, TTarget> expression)
 {
     CheckReadOnly();
     if (expression == null)
     {
         throw new ArgumentNullException("expression");
     }
     _creator = new LambdaCreator <TSource, TTarget>(expression);
     return(this);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="GenericCopyStrategy{TBase, TDerived, TConcrete}"/> class.
        /// </summary>
        public GenericCopyStrategy(
            IInstanceCreator <TDerived, TConcrete> creator,
            ICopy <TDerived> copier)
        {
            creator.NotNull(nameof(creator));
            copier.NotNull(nameof(copier));

            this.creator = creator;
            this.copier  = copier;
        }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CreateConvertStrategy{TSource, TConcreteSource, TTarget, TConcreteTarget, TConcreteTargetImpl, TIntention}"/> class.
        /// </summary>
        public CreateConvertStrategy(
            IInstanceCreator <TConcreteTarget, TConcreteTargetImpl> creator,
            IConvert <TConcreteSource, TConcreteTarget, TIntention> converter)
        {
            creator.NotNull(nameof(creator));
            converter.NotNull(nameof(converter));

            this.creator   = creator;
            this.converter = converter;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CreateCopyHelper{TChild,TConcreteChild,TParent}"/> class.
        /// </summary>
        public CreateCopyHelper(
            IInstanceCreator <TChild, TConcreteChild> instanceCreator,
            ICopy <TChild> copy)
        {
            instanceCreator.NotNull(nameof(instanceCreator));
            copy.NotNull(nameof(copy));

            this.instanceCreator = instanceCreator;
            this.copy            = copy;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CreateTargetImplConvertTargetHelper{TSource,TTarget,TTargetImpl,TReverseRelation,TConvertIntention}" /> class.
        /// </summary>
        public CreateTargetImplConvertTargetHelper(
            IInstanceCreator <TTarget, TTargetImpl> instanceCreator,
            IConvert <TSource, TTarget, TConvertIntention> convert)
        {
            instanceCreator.NotNull(nameof(instanceCreator));
            convert.NotNull(nameof(convert));

            this.instanceCreator = instanceCreator;
            this.convert         = convert;
        }
 static DataLoader()
 {
     if (Environment.Is64BitProcess)
     {
         ReaderCreator = new RawReaderMetadata.InstanceCreator();
     }
     else
     {
         ReaderCreator = new MSFileReaderMetadata.InstanceCreator();
     }
 }
示例#15
0
        /// <summary>
        /// Gets the instance from the Session, if available, otherwise creates a new
        /// instance and stores in the Session.
        /// </summary>
        /// <param name="creator">The creator (registration) to create a new instance.</param>
        /// <returns>The instance.</returns>
        public object GetInstance(IInstanceCreator creator)
        {
            object instance = Session[creator.Key];

            if (instance == null)
            {
                instance             = creator.CreateInstance(ContainerCaching.InstanceNotCachedInContainer);
                Session[creator.Key] = instance;
            }

            return(instance);
        }
        public void CreateFactory_returns_null_for_null_type([Frozen] IInstanceCreator creator,
                                                             WebDriverFactoryCreator sut)
        {
            // Arrange
            Mock.Get(creator).Setup(x => x.CreateInstance(It.IsAny <Type>())).Returns((object)null);

            // Act
            var result = sut.GetFactory(null);

            // Assert
            Assert.That(result, Is.Null);
        }
        public void CreateFactory_calls_instance_creator_using_correct_type([Frozen] IInstanceCreator creator,
                                                                            WebDriverFactoryCreator sut)
        {
            // Arrange
            var typeName = typeof(FactoryType).AssemblyQualifiedName;

            // Act
            sut.GetFactory(typeName);

            // Assert
            Mock.Get(creator).Verify(x => x.CreateInstance(typeof(FactoryType)), Times.Once);
        }
        private static IEnumerable <IInstanceCreator> GetMethodCreators(Type targetType, MethodBase method)
        {
            Debug.Assert(targetType != null);
            Debug.Assert(method != null);
            Debug.Assert(method.IsGenericMethod || !targetType.ContainsGenericParameters);

            // Ignore recursive parameters.
            var parameters = method.GetParameters( );

            if (parameters.Any(p => p.ParameterType.Is(targetType) || p.ParameterType.Is(method.DeclaringType)))
            {
                yield break;
            }

            // Retrieve creators for each parameter.
            var availableArguments = parameters.Select((p) => TypeCreator.GetInstanceCreators(p.ParameterType).AsEnumerable( ));

            // Call constructor with all argument permutations.
            foreach (var arguments in Permuter.Permute(availableArguments))
            {
                // If method is concrete, use it.
                if (!method.IsGenericMethod)
                {
                    yield return(WeakInstanceCreator.ForMethod(targetType, method, arguments));
                }
                // Otherwise, try to resolve generic arguments on method.
                else if (method is MethodInfo)
                {
                    var methodInfo = (MethodInfo)method;
                    var bindings   = new BindingCollection(Binding.EmptyBindings);
                    for (int i = 0; i < parameters.Length; ++i)
                    {
                        ParameterInfo    parameter = parameters[i];
                        IInstanceCreator argument  = arguments[i];
                        if (parameter.ParameterType.ContainsGenericParameters)
                        {
                            GenericTypeResolver.GetAssignedGenericArguments(bindings, argument.InstanceType, parameter.ParameterType);
                        }
                    }

                    foreach (LinkList <Binding> b in bindings)
                    {
                        var concreteMethod = GenericTypeResolver.MakeConcreteMethod(methodInfo, b);
                        if (concreteMethod != null)
                        {
                            targetType = concreteMethod.ReturnType;
                            yield return(WeakInstanceCreator.ForMethod(targetType, concreteMethod, arguments));
                        }
                    }
                }
            }
        }
        private static T TestCreator <T>(IInstanceCreator <T> creator)
        {
            var type = typeof(T);

            Assert.NotNull(creator);
            Assert.Equal(type, creator.InstanceType);

            var result = (creator as IInstanceCreator).CreateInstance( );

            Assert.NotNull(result);
            Assert.True(type.IsInstanceOfType(result));

            return((T)result);
        }
示例#20
0
        public ProxyInstanceCreator(IInstanceCreator instanceCreator, ModelMetadata modelMetadata)
        {
            if (instanceCreator == null)
            {
                throw new ArgumentNullException(nameof(instanceCreator));
            }
            if (modelMetadata == null)
            {
                throw new ArgumentNullException(nameof(modelMetadata));
            }

            _entityTypes     = modelMetadata.EntityTypes;
            _instanceCreator = instanceCreator;
            _constraints     = modelMetadata.Constraints;
        }
        public void CreateFactory_returns_result_from_instance_creator([Frozen] IInstanceCreator creator,
                                                                       WebDriverFactoryCreator sut,
                                                                       ICreatesWebDriver expectedResult)
        {
            // Arrange
            var typeName = typeof(FactoryType).AssemblyQualifiedName;

            Mock.Get(creator).Setup(x => x.CreateInstance(typeof(FactoryType))).Returns(expectedResult);

            // Act
            var result = sut.GetFactory(typeName);

            // Assert
            Assert.That(result, Is.SameAs(expectedResult));
        }
示例#22
0
        /// <summary>
        /// Gets the instance from cache, if available, otherwise creates a new
        /// instance and caches it.
        /// </summary>
        /// <param name="creator">The creator (registration) to create a new instance.</param>
        /// <returns>The instance.</returns>
        public object GetInstance(IInstanceCreator creator)
        {
            Cache cache = HttpRuntime.Cache;

            object instance = cache[creator.Key];

            if (instance == null)
            {
                instance = creator.CreateInstance(ContainerCaching.InstanceNotCachedInContainer);

                cache.Insert(creator.Key, instance, _dependencies, _absoluteExpiration,
                             _slidingExpiration, _priority, _onRemoveCallback);
            }

            return(instance);
        }
示例#23
0
        /// <summary>
        /// Gets an instance from the thread local storage, or creates a new instance if not found.
        /// </summary>
        /// <param name="creator">The IInstanceCreate to use to get the Key and create new if required.</param>
        /// <returns>The instance.</returns>
        public object GetInstance(IInstanceCreator creator)
        {
            object instance = null;

            // if it is a new thread then the localStorage needs to be initialized;
            if (localStorage == null)
            {
                localStorage = new Dictionary <string, object>();
            }

            if (!localStorage.TryGetValue(creator.Key, out instance))
            {
                instance = creator.CreateInstance(ContainerCaching.InstanceNotCachedInContainer);
                localStorage[creator.Key] = instance;
            }

            return(instance);
        }
        private static ReadOnlyCollection <IInstanceCreator> GetInstanceCreators(Type targetType)
        {
            Debug.Assert(targetType != null);
            Debug.Assert(targetType.IsVisible);

            // If creators have not been cached, or are in the process of being cached, take lock and re-check cache.
            ReadOnlyCollection <IInstanceCreator> cached;

            if (!creatorCache_.TryGetValue(targetType, out cached) || object.ReferenceEquals(cached, TempCreators))
            {
                bool   isInstanceCreator = targetType.IsGenericType && targetType.GetGenericTypeDefinition( ) == typeof(IInstanceCreator <>);
                Type[] availableTypes    = isInstanceCreator ? null : TypeLoader.GetUsableTypes(targetType).ToArray( );
                lock ( creatorCacheLock_ ) {
                    if (!TypeCreator.creatorCache_.ContainsKey(targetType))
                    {
                        TypeCreator.creatorCache_[targetType] = TempCreators;
                        ReadOnlyCollection <IInstanceCreator> creators;

                        // If target type is for IInstanceCreator<T>, wrap creators for T.
                        if (isInstanceCreator)
                        {
                            Type innerTargetType = targetType.GetGenericArguments( )[0];
                            var  innerCreators   = TypeCreator.GetCreators(innerTargetType);

                            var outerCreators = new IInstanceCreator[innerCreators.Count];
                            for (int i = 0; i < outerCreators.Length; ++i)
                            {
                                outerCreators[i] = WeakInstanceCreator.ForInstanceCreator(targetType, innerCreators[i]);
                            }
                            creators = outerCreators.ToReadOnlyCollection( );
                        }
                        // Otherwise, get creators for type directly.
                        else
                        {
                            creators = GetInstanceCreators(targetType, availableTypes);
                        }

                        TypeCreator.creatorCache_[targetType] = creators;
                    }
                }
            }

            return(TypeCreator.creatorCache_[targetType]);
        }
        public SingleParameterTester([NotNull] ILogger logger,
                                     [NotNull] IResultMessageBuilder builder,
                                     [NotNull] IParameterCreator parameterCreator,
                                     [NotNull] IInstanceCreator instanceCreator)
        {
            Guard.ArgumentNotNull(logger,
                                  nameof(logger));
            Guard.ArgumentNotNull(builder,
                                  nameof(builder));
            Guard.ArgumentNotNull(parameterCreator,
                                  nameof(parameterCreator));
            Guard.ArgumentNotNull(instanceCreator,
                                  nameof(instanceCreator));

            _logger           = logger;
            _builder          = builder;
            _parameterCreator = parameterCreator;
            _creator          = instanceCreator;
        }
示例#26
0
        public MethodBodyBuilder(IMetadataHost host, IEnumerable<IParameterDefinition> parameters)
        {
            reflector = new UnitReflector(host);
            locals = new LocalVariableBindings(reflector);
            define = new DefinitionBuilder(reflector, locals, host.NameTable);
            create = new InstanceCreator(reflector, locals);
            declare = new DeclarationBuilder(define);
            call = new MethodCallBuilder(host, reflector, locals);
            changeType = new Converter(reflector);
            operators = new TypeOperatorBuilder(reflector);
            constant = new CompileTimeConstantBuilder(reflector);
            @if = new IfStatementBuilder();
            @return = new CodeReturnStatementBuilder();
            anonymousMethod = new AnonymousMethodTypeOptions(host, reflector);
            statement = new StatementBuilder();
            @params = new ParameterBindings();

            foreach (var parameter in parameters)
            {
                @params.AddBinding(parameter);
            }
        }
示例#27
0
        private void initialize(SharpSerializerBinarySettings settings)
        {
            this.InstanceCreator = settings.InstanceCreator ?? new DefaultInstanceCreator();

            // PropertiesToIgnore
            PropertyProvider.PropertiesToIgnore = settings.AdvancedSettings.PropertiesToIgnore;
            PropertyProvider.AttributesToIgnore = settings.AdvancedSettings.AttributesToIgnore;

            //RootName
            RootName = settings.AdvancedSettings.RootName;

            // TypeNameConverter)
            ITypeNameConverter typeNameConverter = settings.AdvancedSettings.TypeNameConverter ??
                                                   DefaultInitializer.GetTypeNameConverter(
                settings.IncludeAssemblyVersionInTypeName,
                settings.IncludeCultureInTypeName,
                settings.IncludePublicKeyTokenInTypeName);


            // Create Serializer and Deserializer
            IBinaryReader reader = null;
            IBinaryWriter writer = null;

            if (settings.Mode == BinarySerializationMode.Burst)
            {
                // Burst mode
                writer = new BurstBinaryWriter(typeNameConverter, settings.Encoding);
                reader = new BurstBinaryReader(typeNameConverter, settings.Encoding);
            }
            else
            {
                // Size optimized mode
                writer = new SizeOptimizedBinaryWriter(typeNameConverter, settings.Encoding);
                reader = new SizeOptimizedBinaryReader(typeNameConverter, settings.Encoding);
            }

            _deserializer = new BinaryPropertyDeserializer(reader);
            _serializer   = new BinaryPropertySerializer(writer);
        }
        /// <summary>
        /// Verifies all the classes that inherit MapperBase have valid AutoMapper configuration.  To do this it needs to create an instance of each.
        /// </summary>
        /// <param name="instanceCreator">
        ///     If you are using an IOC container, pass in a class that uses your IOC container to create
        ///     the instance.  If you don't pass one, it will create instances of mappers using reflection.  This may work unless
        ///     you have mappers that do not have a default constructor with no parameters.
        /// 
        ///     For example, in an MVC app, check out DotNetAppStarterKit.SampleMvc.Application.Mapping at:
        ///     https://github.com/nootn/DotNetAppStarterKit/blob/master/DotNetAppStarterKit.SampleMvc/Application/Mapping/MvcInstanceCreator.cs
        /// </param>
        public static void AssertConfigurationIsValidInAllMappers(IInstanceCreator instanceCreator = null)
        {
            if (instanceCreator == null)
            {
                //Select a default instance creator if none supplied
                instanceCreator = new ReflectionInstanceCreator();
            }

            var exceptions = new List<Exception>();
            foreach (var currAssembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var mapperTypes = from x in currAssembly.GetTypes()
                    let y = x.BaseType
                    where !x.IsAbstract && !x.IsInterface &&
                          y != null && y.IsGenericType &&
                          y.GetGenericTypeDefinition() == typeof (MapperBase<,>)
                    select x;

                foreach (var currType in mapperTypes)
                {
                    dynamic inst = instanceCreator.CreateInstance(currType);
                    try
                    {
                        inst.EnsureMapExists();
                    }
                    catch (Exception ex)
                    {
                        exceptions.Add(ex);
                    }
                }
            }

            if (exceptions.Any())
            {
                throw new AggregateException(
                    "One or more classes that inherit MapperBase<,> have failed configuration assertion.", exceptions);
            }
        }
示例#29
0
        private static IEnumerable <IInstanceCreator> GetReaderCreatorsFromDirectory(string directoryPath)
        {
            var assemblyPaths = Directory.EnumerateFiles(directoryPath, "*.dll", SearchOption.TopDirectoryOnly);

            foreach (var assemblyPath in assemblyPaths)
            {
                IEnumerable <IInstanceCreator> creators = new IInstanceCreator[0];
                try
                {
                    var assembly = Assembly.LoadFrom(assemblyPath);
                    creators = GetReaderCreatorsFromAssembly(assembly);
                }
                catch
                {
                    // do nothing?
                }

                foreach (var creator in creators)
                {
                    yield return(creator);
                }
            }
        }
            public static IInstanceCreator ForInstanceCreator(Type targetType, IInstanceCreator creator)
            {
                Debug.Assert(creator != null);
                Debug.Assert(targetType != null);
                Debug.Assert(targetType.IsGenericType && targetType.GetGenericTypeDefinition( ) == typeof(IInstanceCreator <>));

                IInstanceCreator finalCreator      = creator;
                Type             creatorType       = creator.GetType( );
                Type             targetCreatedType = targetType.GetGenericArguments( )[0];

                // Ensure target type is closed.
                Type finalTargetType = targetType;

                if (finalTargetType.ContainsGenericParameters)
                {
                    targetCreatedType = GenericTypeResolver.GetCorrespondingBaseTypes(finalCreator.InstanceType, targetCreatedType).Single( );
                    finalTargetType   = typeof(IInstanceCreator <>).MakeGenericType(targetCreatedType);
                }

                // If the creator does not have the same type as the target, wrap the creator to return instances of the target base type.
                if (!creatorType.Is(finalTargetType))
                {
                    Type actualCreatedType = creatorType.GetInterfaces( )
                                             .Single(i => i.IsGenericType && i.GetGenericTypeDefinition( ) == typeof(IInstanceCreator <>))
                                             .GetGenericArguments( )[0];

                    Type wrapperType = typeof(InstanceCreatorWrapper <,>).MakeGenericType(targetCreatedType, actualCreatedType);
                    finalCreator = (IInstanceCreator)Activator.CreateInstance(wrapperType, creator);
                }

                // Get IInstanceCreator to return the given creator instance.
                Type funcType       = typeof(Func <>).MakeGenericType(finalTargetType);
                var  lambda         = Expression.Lambda(funcType, Expression.Constant(finalCreator, finalTargetType));
                var  nestingCreator = WeakInstanceCreator.ForDelegate(lambda.Compile( ));

                return(nestingCreator);
            }
示例#31
0
 private void Initialize()
 {
     if (!_initialized)
     {
         lock (_lockObj)
         {
             if (!_initialized)
             {
                 var context = new ConventionContext(_container, typeof(TSource), typeof(TTarget), _options);
                 _container.Conventions.Apply(context);
                 _targetMembers = context.TargetMembers;
                 _memberMappers = new MemberMapperCollection(_container, _options);
                 foreach (var mapping in context.Mappings)
                 {
                     _memberMappers.Set(mapping.TargetMember, mapping.SourceMember, mapping.Converter);
                 }
                 _creator = context.Creator != null
                     ? (IInstanceCreator <TTarget>) new ConventionCreator <TTarget>(context.Creator)
                     : new DefaultCreator <TTarget>();
                 _initialized = true;
             }
         }
     }
 }
示例#32
0
 public ExtendedObjectBuilder(IInstanceCreator creator, ObjectBuilderContext objectBuilderContext, IContextFactory contextFactory)
     : base(creator, objectBuilderContext, contextFactory)
 {
     this.contextFactory = contextFactory;
 }
 public ServiceFactoryProvider(IInstanceCreator instanceCreator)
 {
     InstanceCreator = instanceCreator;
 }
示例#34
0
 public object GetInstance(NancyContainer container, IInstanceCreator creator)
 {
     return creator.CreateInstance(container);
 }