Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static IDynamicConstructor GetDynamicConstructor(Type objectType, params Type[] parameterTypes)
        {
            if (parameterTypes == null)
            {
                parameterTypes = Type.EmptyTypes;
            }
            MethodCacheKey      key = MethodCacheKey.Create(objectType.FullName, objectType.Name, parameterTypes);
            IDynamicConstructor dynamicConstructor = null;

            if (!_dynamicConstructors.TryGetValue(key, out dynamicConstructor))
            {
                lock (_syncObj)
                {
                    if (!_dynamicConstructors.TryGetValue(key, out dynamicConstructor))
                    {
                        ConstructorInfo ctor = objectType.GetConstructor(parameterTypes);
                        if (ctor != null)
                        {
                            dynamicConstructor = DynamicConstructor.Create(ctor);
                            if (dynamicConstructor != null)
                            {
                                _dynamicConstructors.Add(key, dynamicConstructor);
                            }
                        }
                    }
                }
            }

            return(dynamicConstructor);
        }
Пример #2
0
        public static IDynamicConstructor GetDynamicConstructor(Type objectType, IDictionary <string, object> namedArgValues)
        {
            IDictionary <string, object> namedParamValues = namedArgValues == null ? new Dictionary <string, object>() : namedArgValues;
            DynamicConstructorCacheKey   key = new DynamicConstructorCacheKey(objectType, namedParamValues);
            IDynamicConstructor          dynamicConstructor = null;

            if (!_namedArgumentDynamicConstructors.TryGetValue(key, out dynamicConstructor))
            {
                lock (_syncObj)
                {
                    if (!_namedArgumentDynamicConstructors.TryGetValue(key, out dynamicConstructor))
                    {
                        ConstructorInfo constructorInfo = ReflectionHelper.GetConstructorByNamedArgumentValues(objectType, namedArgValues);
                        dynamicConstructor = DynamicConstructor.Create(constructorInfo);

                        if (dynamicConstructor != null)
                        {
                            _namedArgumentDynamicConstructors.Add(key, dynamicConstructor);
                        }
                    }
                }
            }

            return(dynamicConstructor);
        }
        /// <summary>
        /// Registers resource handler and maps it to the specified protocol name.
        /// </summary>
        /// <remarks>
        /// <p>
        /// If the mapping already exists, the existing mapping will be
        /// silently overwritten with the new mapping.
        /// </p>
        /// </remarks>
        /// <param name="protocolName">
        /// The protocol to add (or override).
        /// </param>
        /// <param name="handlerType">
        /// The concrete implementation of the
        /// <see cref="Oragon.Spring.Core.IO.IResource"/> interface that will handle
        /// the specified protocol.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// If the supplied <paramref name="protocolName"/> is
        /// <see langword="null"/> or contains only whitespace character(s); or
        /// if the supplied <paramref name="handlerType"/> is
        /// <see langword="null"/>.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// If the supplied <paramref name="handlerType"/> is not a
        /// <see cref="Type"/> that derives from the
        /// <see cref="Oragon.Spring.Core.IO.IResource"/> interface; or (having passed
        /// this first check), the supplied <paramref name="handlerType"/>
        /// does not expose a constructor that takes a single
        /// <see cref="System.String"/> parameter.
        /// </exception>
        public static void RegisterResourceHandler(string protocolName, Type handlerType)
        {
            #region Sanity Checks

            AssertUtils.ArgumentHasText(protocolName, "protocolName");
            AssertUtils.ArgumentNotNull(handlerType, "handlerType");
            if (!typeof(IResource).IsAssignableFrom(handlerType))
            {
                throw new ArgumentException(
                          string.Format("[{0}] does not implement [{1}] interface (it must).", handlerType.FullName, typeof(IResource).FullName));
            }

            #endregion

            lock (syncRoot)
            {
                //SecurityCritical.ExecutePrivileged( new SecurityPermission(SecurityPermissionFlag.Infrastructure), delegate
                //{
                // register generic uri parser for this scheme
                if (!UriParser.IsKnownScheme(protocolName))
                {
                    UriParser.Register(new TolerantUriParser(), protocolName, 0);
                }
                //});
                IDynamicConstructor ctor = GetResourceConstructor(handlerType);
                resourceHandlers[protocolName] = ctor;
            }
        }
        public void ObjectInstantiatonTests()
        {
            int numIterations = 1000000;


            start = DateTime.Now;
            Type t = typeof(AccountCreditDao);

            for (int i = 0; i < numIterations; i++)
            {
                //ObjectUtils.IsInstantiable(t);
                IDynamicConstructor dc = DynamicConstructor.Create(t.GetConstructor(Type.EmptyTypes));
                dc.Invoke(ObjectUtils.EmptyObjects);
            }
            stop = DateTime.Now;
            double timeElapsed = Elapsed;

            PrintTest("SafeConstructor", numIterations, timeElapsed);

            start = DateTime.Now;
            for (int i = 0; i < numIterations; i++)
            {
                ObjectUtils.InstantiateType(typeof(AccountCreditDao));
            }
            stop        = DateTime.Now;
            timeElapsed = Elapsed;
            PrintTest("InstantiateType", numIterations, timeElapsed);
        }
Пример #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DbProvider"/> class.
 /// </summary>
 /// <param name="dbMetadata">The db metadata.</param>
 public DbProvider(IDbMetadata dbMetadata)
 {
     this.dbMetadata = dbMetadata;
     newCommand = DynamicConstructor.Create(dbMetadata.CommandType.GetConstructor(Type.EmptyTypes));
     newConnection = DynamicConstructor.Create(dbMetadata.ConnectionType.GetConstructor(Type.EmptyTypes));
     newCommandBuilder = DynamicConstructor.Create(dbMetadata.CommandBuilderType.GetConstructor(Type.EmptyTypes));
     newDataAdapter = DynamicConstructor.Create(dbMetadata.DataAdapterType.GetConstructor(Type.EmptyTypes));
     newParameter = DynamicConstructor.Create(dbMetadata.ParameterType.GetConstructor(Type.EmptyTypes));
 }
Пример #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DbProvider"/> class.
 /// </summary>
 /// <param name="dbMetadata">The db metadata.</param>
 public DbProvider(IDbMetadata dbMetadata)
 {
     this.dbMetadata   = dbMetadata;
     newCommand        = DynamicConstructor.Create(dbMetadata.CommandType.GetConstructor(Type.EmptyTypes));
     newConnection     = DynamicConstructor.Create(dbMetadata.ConnectionType.GetConstructor(Type.EmptyTypes));
     newCommandBuilder = DynamicConstructor.Create(dbMetadata.CommandBuilderType.GetConstructor(Type.EmptyTypes));
     newDataAdapter    = DynamicConstructor.Create(dbMetadata.DataAdapterType.GetConstructor(Type.EmptyTypes));
     newParameter      = DynamicConstructor.Create(dbMetadata.ParameterType.GetConstructor(Type.EmptyTypes));
 }
Пример #7
0
 /// <summary>
 /// Creates a new instance of the safe constructor wrapper.
 /// </summary>
 /// <param name="constructor">Constructor to wrap.</param>
 public SafeConstructor(ConstructorInfo constructor)
 {
     this.constructorInfo = constructor;
     if (constructor.IsPublic &&
         ReflectionUtils.IsTypeVisible(constructor.DeclaringType, DynamicReflectionManager.ASSEMBLY_NAME))
     {
         this.dynamicConstructor = DynamicConstructor.Create(constructor);
         this.isOptimized        = true;
     }
 }
Пример #8
0
        /// <summary>
        /// Uses reflection to create an object using its
        /// default constructor.
        /// </summary>
        /// <param name="objectType">Type of object to create.</param>
        public static object CreateInstance(Type objectType)
        {
            IDynamicConstructor ctor = DynamicConstructorCache.GetDynamicConstructor(objectType, Type.EmptyTypes);

            if (ctor == null)
            {
                ThrowHelper.ThrowNotImplementedException(ReflectionSR.DefaultConstructorMethodNotImplemented, objectType.FullName);
            }

            return(ctor.Invoke(null));
        }
Пример #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="objectType"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static object CreateInstance(Type objectType, params object[] parameters)
        {
            IDynamicConstructor ctor = DynamicConstructorCache.GetDynamicConstructor(objectType, parameters);

            if (ctor == null)
            {
                ThrowHelper.ThrowNotImplementedException(ReflectionSR.ConstructorNotImplemented, objectType.FullName, TypeHelper.GetTypesString(parameters));
            }

            return(ctor.Invoke(parameters));
        }
Пример #10
0
        public static object CreateInstance(Type objectType, IDictionary <string, object> namedArgValues)
        {
            object target            = null;
            IDynamicConstructor ctor = DynamicConstructorCache.GetDynamicConstructor(objectType, namedArgValues);

            if (ctor != null)
            {
                target = ctor.Invoke(namedArgValues.Values.ToArray());
            }

            return(target);
        }
        public void TestConstructors()
        {
            IDynamicConstructor newInventor = DynamicConstructor.Create(
                typeof(Inventor).GetConstructor(new Type[] { typeof(string), typeof(DateTime), typeof(string) }));
            Inventor ana = (Inventor)newInventor.Invoke(new object[] { "Ana Maria Seovic", new DateTime(2004, 8, 14), "Serbian" });

            Assert.AreEqual("Ana Maria Seovic", ana.Name);

            IDynamicConstructor newDate = DynamicConstructor.Create(
                typeof(DateTime).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int) }));

            Assert.AreEqual(DateTime.Today, newDate.Invoke(new object[] { DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day }));
        }
Пример #12
0
 /// <summary>
 /// Returns dynamic constructor if one exists.
 /// </summary>
 /// <param name="constructor">Constructor to look up.</param>
 /// <param name="createCallback">callback function that will be called to create the dynamic constructor</param>
 /// <returns>An <see cref="IDynamicConstructor"/> for the given constructor.</returns>
 internal static IDynamicConstructor GetDynamicConstructor(ConstructorInfo constructor, CreateConstructorCallback createCallback)
 {
     lock (constructorCache.SyncRoot)
     {
         IDynamicConstructor dynamicConstructor = (IDynamicConstructor)constructorCache[constructor];
         if (dynamicConstructor == null)
         {
             dynamicConstructor            = createCallback(constructor);
             constructorCache[constructor] = dynamicConstructor;
         }
         return(dynamicConstructor);
     }
 }
Пример #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DbProvider"/> class.
        /// </summary>
        /// <param name="dbMetadata">The db metadata.</param>
        public DbProvider(IDbMetadata dbMetadata)
        {
            this.dbMetadata = dbMetadata;
            newCommand = DynamicConstructor.Create(dbMetadata.CommandType.GetConstructor(Type.EmptyTypes));
            
            // Oracle needs custom bind by name property set to true as it's false by default
            var bindByNameProperty = dbMetadata.CommandType.GetProperty("BindByName");
            if (bindByNameProperty != null && bindByNameProperty.CanWrite)
            {
                commandBindByName = DynamicProperty.Create(bindByNameProperty);
            }

            newConnection = DynamicConstructor.Create(dbMetadata.ConnectionType.GetConstructor(Type.EmptyTypes));
            newCommandBuilder = DynamicConstructor.Create(dbMetadata.CommandBuilderType.GetConstructor(Type.EmptyTypes));
            newDataAdapter = DynamicConstructor.Create(dbMetadata.DataAdapterType.GetConstructor(Type.EmptyTypes));
            newParameter = DynamicConstructor.Create(dbMetadata.ParameterType.GetConstructor(Type.EmptyTypes));
        }
Пример #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DbProvider"/> class.
        /// </summary>
        /// <param name="dbMetadata">The db metadata.</param>
        public DbProvider(IDbMetadata dbMetadata)
        {
            this.dbMetadata = dbMetadata;
            newCommand      = DynamicConstructor.Create(dbMetadata.CommandType.GetConstructor(Type.EmptyTypes));

            // Oracle needs custom bind by name property set to true as it's false by default
            var bindByNameProperty = dbMetadata.CommandType.GetProperty("BindByName");

            if (bindByNameProperty != null && bindByNameProperty.CanWrite)
            {
                commandBindByName = DynamicProperty.Create(bindByNameProperty);
            }

            newConnection     = DynamicConstructor.Create(dbMetadata.ConnectionType.GetConstructor(Type.EmptyTypes));
            newCommandBuilder = DynamicConstructor.Create(dbMetadata.CommandBuilderType.GetConstructor(Type.EmptyTypes));
            newDataAdapter    = DynamicConstructor.Create(dbMetadata.DataAdapterType.GetConstructor(Type.EmptyTypes));
            newParameter      = DynamicConstructor.Create(dbMetadata.ParameterType.GetConstructor(Type.EmptyTypes));
        }
Пример #15
0
        /// <summary>
        /// Returns a <see cref="Spring.Core.IO.IResource"/> that has been
        /// mapped to the protocol of the supplied <paramref name="resourceName"/>.
        /// </summary>
        /// <param name="resourceName">The name of the resource.</param>
        /// <returns>
        /// A new <see cref="Spring.Core.IO.IResource"/> instance for the
        /// supplied <paramref name="resourceName"/>.
        /// </returns>
        /// <exception cref="System.UriFormatException">
        /// If a <see cref="Spring.Core.IO.IResource"/> <see cref="System.Type"/>
        /// mapping does not exist for the supplied <paramref name="resourceName"/>.
        /// </exception>
        /// <exception cref="System.Exception">
        /// In the case of any errors arising from the instantiation of the
        /// returned <see cref="Spring.Core.IO.IResource"/> instance.
        /// </exception>
        /// <seealso cref="ResourceHandlerRegistry.RegisterResourceHandler(string, Type)"/>
        public IResource GetResource(string resourceName)
        {
            string protocol = GetProtocol(resourceName);

            if (protocol == null)
            {
                protocol     = DefaultResourceProtocol;
                resourceName = protocol + ProtocolSeparator + resourceName;
            }

            IDynamicConstructor handler = ResourceHandlerRegistry.GetResourceHandler(protocol);

            if (handler == null)
            {
                throw new UriFormatException("Resource handler for the '" + protocol + "' protocol is not defined.");
            }

            return((IResource)handler.Invoke(new object[] { resourceName }));
        }
        //[Test]
        public void PerformanceTests()
        {
            int    n = 10000000;
            object x = null;

            // new Inventor()
            start = DateTime.Now;
            for (int i = 0; i < n; i++)
            {
                x = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian");
            }
            stop = DateTime.Now;
            PrintTest("new Inventor() (direct)", n, Elapsed);

            start = DateTime.Now;
            IDynamicConstructor newInventor = DynamicConstructor.Create(
                typeof(Inventor).GetConstructor(new Type[] { typeof(string), typeof(DateTime), typeof(string) }));

            for (int i = 0; i < n; i++)
            {
                object[] args = new object[] { "Nikola Tesla", new DateTime(1856, 7, 9), "Serbian" };
                x = newInventor.Invoke(args);
            }
            stop = DateTime.Now;
            PrintTest("new Inventor() (dynamic reflection)", n, Elapsed);

            start = DateTime.Now;
            ConstructorInfo newInventorCi =
                typeof(Inventor).GetConstructor(new Type[] { typeof(string), typeof(DateTime), typeof(string) });

            for (int i = 0; i < n; i++)
            {
                object[] args = new object[] { "Nikola Tesla", new DateTime(1856, 7, 9), "Serbian" };
                x = newInventorCi.Invoke(args);
            }
            stop = DateTime.Now;
            PrintTest("new Inventor() (standard reflection)", n, Elapsed);
        }
 public CreateControlCollectionWrapper(IDynamicConstructor ctor)
 {
     _ctor = ctor;
 }
 /// <summary>
 /// Creates a new instance of the safe constructor wrapper.
 /// </summary>
 /// <param name="constructor">Constructor to wrap.</param>
 public SafeConstructor(ConstructorInfo constructor)
 {
     this.constructorInfo = constructor;
     if (constructor.IsPublic &&
         ReflectionUtils.IsTypeVisible(constructor.DeclaringType, DynamicReflectionManager.ASSEMBLY_NAME))
     {
         this.dynamicConstructor = DynamicConstructor.Create(constructor);
         this.isOptimized = true;
     }
 }
 public CreateControlCollectionWrapper(IDynamicConstructor ctor)
 {
     _ctor = ctor;
 }