コード例 #1
0
            static FormatterCache()
            {
                var ti = typeof(T);

                if (ti.IsNullable())
                {
#if NET40
                    ti = ti.GenericTypeArguments()[0];
#else
                    ti = ti.GenericTypeArguments[0];
#endif

                    var innerFormatter = DynamicUnionResolver.Instance.GetFormatterDynamic(ti);
                    if (innerFormatter == null)
                    {
                        return;
                    }
                    formatter = (IMessagePackFormatter <T>)ActivatorUtils.CreateInstance(typeof(StaticNullableFormatter <>).GetCachedGenericType(ti), new object[] { innerFormatter });
                    return;
                }

                var formatterTypeInfo = BuildType(typeof(T));
                if (formatterTypeInfo == null)
                {
                    return;
                }

                formatter = (IMessagePackFormatter <T>)ActivatorUtils.FastCreateInstance(formatterTypeInfo.AsType());
            }
コード例 #2
0
        private object GetValue(object obj, int index)
        {
            PropertyInfo prop;
            FieldInfo    field;

            if ((prop = members[index] as PropertyInfo) != null)
            {
                if (obj == null)
                {
                    // ## 苦竹 修改 ##
                    //return Helpers.IsValueType(prop.PropertyType) ? Activator.CreateInstance(prop.PropertyType) : null;
                    return(Helpers.IsValueType(prop.PropertyType) ? ActivatorUtils.FastCreateInstance(prop.PropertyType) : null);
                }
                return(prop.GetValue(obj, null));
            }
            else if ((field = members[index] as FieldInfo) != null)
            {
                if (obj == null)
                {
                    // ## 苦竹 修改 ##
                    //return Helpers.IsValueType(field.FieldType) ? Activator.CreateInstance(field.FieldType) : null;
                    return(Helpers.IsValueType(field.FieldType) ? ActivatorUtils.FastCreateInstance(field.FieldType) : null);
                }
                return(field.GetValue(obj));
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
コード例 #3
0
            static FormatterCache()
            {
                var ti = typeof(T);

                if (ti.IsNullable())
                {
                    // build underlying type and use wrapped formatter.
#if NET40
                    ti = ti.GenericTypeArguments()[0];
#else
                    ti = ti.GenericTypeArguments[0];
#endif
                    if (!ti.IsEnum)
                    {
                        return;
                    }

                    var innerFormatter = DynamicEnumAsStringResolver.Instance.GetFormatterDynamic(ti);
                    if (innerFormatter == null)
                    {
                        return;
                    }
                    formatter = (IMessagePackFormatter <T>)ActivatorUtils.CreateInstance(typeof(StaticNullableFormatter <>).GetCachedGenericType(ti), new object[] { innerFormatter });
                    return;
                }
                else if (!ti.IsEnum)
                {
                    return;
                }

                formatter = (IMessagePackFormatter <T>)(object) new EnumAsStringFormatter <T>();
            }
コード例 #4
0
            static FormatterCache()
            {
#if UNITY_WSA && !NETFX_CORE
                var attr = (MessagePackFormatterAttribute)typeof(T).GetCustomAttributes(typeof(MessagePackFormatterAttribute), true).FirstOrDefault();
#else
                var attr = typeof(T).GetCustomAttributeX <MessagePackFormatterAttribute>();
#endif
                if (attr == null)
                {
                    return;
                }

                if (attr.FormatterType == MessagePackSerializer.Typeless.TypelessFormatterType ||
                    attr.FormatterType == MessagePackSerializer.Typeless.DefaultTypelessFormatterType)
                {
                    formatter = (IMessagePackFormatter <T>)MessagePackSerializer.Typeless.TypelessFormatter;
                }
                else
                {
                    if (attr.Arguments == null)
                    {
                        formatter = (IMessagePackFormatter <T>)ActivatorUtils.FastCreateInstance(attr.FormatterType);
                    }
                    else
                    {
                        formatter = (IMessagePackFormatter <T>)ActivatorUtil.CreateInstance(attr.FormatterType, attr.Arguments);
                    }
                }
            }
コード例 #5
0
 public void CreateInstanceAutoFillGenericParameters_GenericTypeWithBaseClassConstraintPassed_ExceptionThrown()
 {
     Assert.Throws <ArgumentException>(() =>
     {
         ActivatorUtils.CreateInstanceAutoFillGenericParameters(typeof(GenericClassWithBaseClassConstraint <>));
     });
 }
コード例 #6
0
        public static object FromObjectDictionary(this IReadOnlyDictionary <string, object> values, Type type)
        {
            var alreadyDict = type == typeof(IReadOnlyDictionary <string, object>);
#endif
            if (alreadyDict)
            {
                return(true);
            }

            if (!toObjectMapCache.TryGetValue(type, out var def))
            {
                toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type);
            }

            var to = ActivatorUtils.FastCreateInstance(type); //type.CreateInstance();

            foreach (var entry in values)
            {
                if (!def.FieldsMap.TryGetValue(entry.Key, out var fieldDef) &&
                    !def.FieldsMap.TryGetValue(entry.Key.ToPascalCase(), out fieldDef) ||
                    entry.Value == null)
                {
                    continue;
                }

                fieldDef.SetValue(to, entry.Value);
            }
            return(to);
        }
コード例 #7
0
        public Activity <TInstance> GetActivity <TActivity, TInstance>(BehaviorContext <TInstance> context)
            where TActivity : class, Activity <TInstance>
        {
            var lifetimeScope = context.GetPayload <ILifetimeScope>();

            return(ActivatorUtils.GetOrCreateInstance <TActivity>(lifetimeScope));
        }
コード例 #8
0
        /// <summary>
        /// Inits the plug-in with configured factory data.
        /// </summary>
        /// <param name="factoryData">Retrieved factory settings.
        /// This parameter is null if no configuration at all
        /// was found.</param>
        public void Init(string factoryData)
        {
            String loggerTypeName;

            try
            {
                // load the factoryData XML
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(factoryData);

                // obtain the logger element and inspect the 'type' attribute
                XmlElement   loggerElement       = (XmlElement)xmlDoc.GetElementsByTagName("logger")[0];
                XmlAttribute loggerTypeAttribute = loggerElement.Attributes[0];
                loggerTypeName = loggerTypeAttribute.Value;
            }
            catch (Exception e)
            {
                DiagnosticLogger.Error(e, "An exception was thrown while trying to parse the given XML configuration [{0}]",
                                       factoryData);
                return;
            }

            ILogger logger = ActivatorUtils.Instantiate <ILogger>(loggerTypeName, DiagnosticLogger);

            if (logger != null)
            {
                Logger = logger;
            }
        }
コード例 #9
0
            static FormatterCache()
            {
                var ti = typeof(T);

                if (ti.IsNullable())
                {
                    // build underlying type and use wrapped formatter.
                    ti = ti.GenericTypeArguments[0];
                    if (!ti.IsEnum)
                    {
                        return;
                    }

                    var innerFormatter = DynamicEnumResolver.Instance.GetFormatterDynamic(ti);
                    if (innerFormatter == null)
                    {
                        return;
                    }
                    formatter = (IMessagePackFormatter <T>)ActivatorUtils.CreateInstance(typeof(StaticNullableFormatter <>).GetCachedGenericType(ti), new object[] { innerFormatter });
                    return;
                }
                else if (!ti.IsEnum)
                {
                    return;
                }

                var formatterTypeInfo = BuildType(typeof(T));

                formatter = (IMessagePackFormatter <T>)ActivatorUtils.FastCreateInstance(formatterTypeInfo.AsType());
            }
コード例 #10
0
        public T GetService <T>(PipeContext context)
            where T : class
        {
            var lifetimeScope = context.GetPayload <ILifetimeScope>();

            return(ActivatorUtils.GetOrCreateInstance <T>(lifetimeScope));
        }
コード例 #11
0
        /// <summary>
        /// Creates a new instance of type.
        /// First looks at JsConfig.ModelFactory before falling back to CreateInstance
        /// </summary>
        public static object New(this Type type)
        {
            //var factoryFn = JsConfig.ModelFactory(type) ?? GetConstructorMethod(type);
            //return factoryFn();
            var factoryFn = JsConfig.ModelFactory(type);

            return(factoryFn != null?factoryFn() : ActivatorUtils.FastCreateInstance(type));
        }
コード例 #12
0
        public static object ConvertFromCollection(object enumerable)
        {
            var to   = ActivatorUtils.FastCreateInstance <ICollection <T> >(typeof(TCollection));
            var from = (IEnumerable <T>)enumerable;

            foreach (var item in from)
            {
                to.Add(item);
            }
            return(to);
        }
コード例 #13
0
        public static IDictionary ParseIDictionary(StringSegment value, Type dictType)
        {
            if (!value.HasValue)
            {
                return(null);
            }

            var index = VerifyAndGetStartIndex(value, dictType);

            var valueParseMethod = Serializer.GetParseStringSegmentFn(typeof(object));

            if (valueParseMethod == null)
            {
                return(null);
            }

            //var to = (IDictionary)dictType.CreateInstance();
            var to = ActivatorUtils.FastCreateInstance <IDictionary>(dictType);

            if (JsonTypeSerializer.IsEmptyMap(value, index))
            {
                return(to);
            }

            var valueLength = value.Length;

            while (index < valueLength)
            {
                var keyValue = Serializer.EatMapKey(value, ref index);
                Serializer.EatMapKeySeperator(value, ref index);
                var elementStartIndex = index;
                var elementValue      = Serializer.EatTypeValue(value, ref index);
                if (!keyValue.HasValue)
                {
                    continue;
                }

                var mapKey = valueParseMethod(keyValue);

                if (elementStartIndex < valueLength)
                {
                    Serializer.EatWhitespace(value, ref elementStartIndex);
                    to[mapKey] = DeserializeType <TSerializer> .ParsePrimitive(elementValue.Value, value.GetChar(elementStartIndex));
                }
                else
                {
                    to[mapKey] = valueParseMethod(elementValue);
                }

                Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
            }

            return(to);
        }
コード例 #14
0
 public static object CreateInstance(Type type, params object[] args)
 {
     if (null == args || 0u > (uint)args.Length)
     {
         return(ActivatorUtils.FastCreateInstance(type));
     }
     else
     {
         return(Activator.CreateInstance(type, args));
     }
 }
コード例 #15
0
        public static object CreateInstance(this Type type)
        {
            if (type == null)
            {
                return(null);
            }

            //var ctorFn = GetConstructorMethod(type);
            //return ctorFn();
            return(ActivatorUtils.FastCreateInstance(type));
        }
コード例 #16
0
        public static T CreateInstance <T>(this Type type)
        {
            if (type == null)
            {
                return(default(T));
            }

            //var ctorFn = GetConstructorMethod(type);
            //return (T)ctorFn();
            return((T)ActivatorUtils.FastCreateInstance(type));
        }
コード例 #17
0
        public static object CreateInstance(string typeName)
        {
            if (string.IsNullOrWhiteSpace(typeName))
            {
                return(null);
            }

            //var ctorFn = GetConstructorMethod(typeName);
            //return ctorFn();
            return(ActivatorUtils.FastCreateInstance(typeName));
        }
コード例 #18
0
        internal static object GetFormatter(Type t)
        {
#if !TEST40
            if (typeof(ITestMessage).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
#else
            if (typeof(ITestMessage).IsAssignableFrom(t))
#endif
            {
                return(ActivatorUtils.FastCreateInstance(typeof(TestMessageFormatter <>).GetCachedGenericType(t)));
            }

            return(null);
        }
コード例 #19
0
        private Func <ServiceResolver, object> ResolveManyEnumerableService(ManyEnumerableServiceDefintion manyEnumerableServiceDefintion)
        {
            var elementDefinitions = manyEnumerableServiceDefintion.ServiceDefinitions.ToArray();
            var elementType        = manyEnumerableServiceDefintion.ElementType;

            return(resolver =>
            {
                var length = elementDefinitions.Length;
                var instance = Array.CreateInstance(elementType, length);
                for (var i = 0; i < length; i++)
                {
                    instance.SetValue(resolver.ResolveDefinition(elementDefinitions[i]), i);
                }
                return ActivatorUtils.CreateManyEnumerable(elementType, instance);
            });
        }
コード例 #20
0
        public override ValueSerializer BuildSerializer(Serializer serializer, Type type,
                                                        CachedReadConcurrentDictionary <Type, ValueSerializer> typeMapping)
        {
            var preserveObjectReferences = serializer.Options.PreserveObjectReferences;
            var ser = new ObjectSerializer(type);

            typeMapping.TryAdd(type, ser);
            var elementSerializer = serializer.GetSerializerByType(typeof(DictionaryEntry));

            ObjectReader reader = (stream, session) =>
            {
                var instance = ActivatorUtils.FastCreateInstance(type) as IDictionary <string, object>;

                if (preserveObjectReferences)
                {
                    session.TrackDeserializedObject(instance);
                }
                var count = stream.ReadInt32(session);
                for (var i = 0; i < count; i++)
                {
                    var entry = (KeyValuePair <string, object>)stream.ReadObject(session);
                    instance.Add(entry);
                }
                return(instance);
            };

            ObjectWriter writer = (stream, obj, session) =>
            {
                if (preserveObjectReferences)
                {
                    session.TrackSerializedObject(obj);
                }
                var dict = obj as IDictionary <string, object>;
                // ReSharper disable once PossibleNullReferenceException
                Int32Serializer.WriteValueImpl(stream, dict.Count, session);
                foreach (var item in dict)
                {
                    stream.WriteObject(item, typeof(DictionaryEntry), elementSerializer,
                                       serializer.Options.PreserveObjectReferences, session);
                    // elementSerializer.WriteValue(stream,item,session);
                }
            };

            ser.Initialize(reader, writer);

            return(ser);
        }
コード例 #21
0
        public void CreateInstanceFromTypeNameTest()
        {
            var dllname = "Generated.dll";

            MakeDll(dllname);
            File.Exists(dllname).Should().BeTrue();

            var asmName  = Path.GetFileNameWithoutExtension(dllname);
            var xelement = new XElement("Ftp", new XAttribute("Class", $"X2, {asmName}"));
            var result   = ActivatorUtils.CreateInstanceFromTypeName <I1>(xelement);

            result.Should().NotBeNull();
            (result is I1).Should().BeTrue();

            File.Delete(dllname);
            File.Exists(dllname).Should().BeFalse();
        }
コード例 #22
0
        public void CreateInstanceFromTypeNameTestOtherDir()
        {
            var otherDirname    = "Other";
            var dllNameOtherDir = Path.Combine(otherDirname, "Generated2.dll");

            MakeDll(dllNameOtherDir);
            var asmName  = Path.GetFileNameWithoutExtension(dllNameOtherDir);
            var xelement = new XElement("Ftp", new XAttribute("Class", $"X2, {asmName}"));
            var result   = ActivatorUtils.CreateInstanceFromTypeName <I1>(xelement);

            result.Should().BeNull();

            var xelementWithExtraPath = new XElement("Ftp", new XAttribute("Class", $"X2, {asmName}"), new XAttribute("ExtraPaths", otherDirname));

            result = ActivatorUtils.CreateInstanceFromTypeName <I1>(xelementWithExtraPath);
            result.Should().NotBeNull();
            (result is I1).Should().BeTrue();
        }
コード例 #23
0
            static FormatterCache()
            {
                Interlocked.CompareExchange(ref s_isFreezed, Locked, Unlocked);

                var formatters = Volatile.Read(ref s_formatters);

                foreach (var item in formatters)
                {
                    foreach (var implInterface in item.GetType().GetTypeInfo().ImplementedInterfaces)
                    {
#if NET40
                        if (implInterface.IsGenericType && implInterface.GenericTypeArguments()[0] == typeof(T))
#else
                        if (implInterface.IsGenericType && implInterface.GenericTypeArguments[0] == typeof(T))
#endif
                        {
                            Formatter = (IMessagePackFormatter <T>)item;
                            return;
                        }
                    }
                }

                var resolvers = Volatile.Read(ref s_resolvers);
                foreach (var item in resolvers)
                {
                    var f = item.GetFormatter <T>();
                    if (f != null)
                    {
                        Formatter = f;
                        return;
                    }
                }

                {
                    var f = MessagePackStandardResolver.TypelessObjectResolver.GetFormatter <T>();
                    if (f != null)
                    {
                        Formatter = f;
                        return;
                    }
                }

                Formatter = ActivatorUtils.FastCreateInstance <IMessagePackFormatter <T> >(typeof(DynamicProxyFormatter <>).GetCachedGenericType(typeof(T)));
            }
コード例 #24
0
        /// <summary>
        /// Creates a factory based on a given configuration.
        /// If the factory provides invalid information, an error is logged through
        /// the internal logger, and a <see cref="NOPLoggerFactory"/> returned.
        /// </summary>
        /// <param name="factoryConfiguration">The configuration that provides type
        /// information for the <see cref="ILoggerFactory"/> that is being created.</param>
        /// <returns>Factory instance.</returns>
        private ILoggerFactory CreateFactoryInstance(FactoryConfigurationElement factoryConfiguration)
        {
            ILoggerFactory             factory = ActivatorUtils.Instantiate <ILoggerFactory>(factoryConfiguration.Type);
            IConfigurableLoggerFactory cf      = factory as IConfigurableLoggerFactory;

            // If the factory is configurable, invoke its Init method
            if (cf != null)
            {
                cf.Init(factoryConfiguration.FactoryData);
            }
            else
            {
                if (!string.IsNullOrEmpty(factoryConfiguration.FactoryData))
                {
                    throw new ConfigurationErrorsException("Factory " + factoryConfiguration.Type + " does not implement IConfigurableLoggerFactory.");
                }
            }

            return(factory);
        }
コード例 #25
0
        object CreateInstance(ProtoReader source, bool includeLocalCallback)
        {
            //Helpers.DebugWriteLine("* creating : " + forType.FullName);
            object obj;

            if (factory != null)
            {
                obj = InvokeCallback(factory, null, source.Context);
            }
            else if (useConstructor)
            {
                if (!hasConstructor)
                {
                    TypeModel.ThrowCannotCreateInstance(constructType);
                }
                // ## 苦竹 修改 ##
                //        obj = Activator.CreateInstance(constructType
                //#if !(CF || SILVERLIGHT || WINRT || PORTABLE || NETSTANDARD1_3 || NETSTANDARD1_4)
                //                    , nonPublic: true
                //#endif
                //                    );
                obj = ActivatorUtils.FastCreateInstance(constructType);
            }
            else
            {
                obj = BclHelpers.GetUninitializedObject(constructType);
            }
            ProtoReader.NoteObject(obj, source);
            if (baseCtorCallbacks != null)
            {
                for (int i = 0; i < baseCtorCallbacks.Length; i++)
                {
                    InvokeCallback(baseCtorCallbacks[i], obj, source.Context);
                }
            }
            if (includeLocalCallback && callbacks != null)
            {
                InvokeCallback(callbacks.BeforeDeserialize, obj, source.Context);
            }
            return(obj);
        }
コード例 #26
0
        /// <summary>
        /// Creates a factory based on a given configuration.
        /// If the factory provides invalid information, an error is logged through
        /// the internal logger, and a <see cref="NullLoggerFactory"/> returned.
        /// </summary>
        /// <param name="factoryConfiguration">The configuration that provides type
        /// information for the <see cref="ILoggerFactory"/> that is being created.</param>
        /// <returns>Factory instance.</returns>
        private ILoggerFactory CreateFactoryInstance(FactoryConfigurationElement factoryConfiguration)
        {
            ILoggerFactory factory = ActivatorUtils.Instantiate <ILoggerFactory>(
                factoryConfiguration.Type, DiagnosticLogger);

            //if the factory is configurable, invoke its Init method
            IConfigurableLoggerFactory cf = factory as IConfigurableLoggerFactory;

            if (cf != null)
            {
                cf.Init(factoryConfiguration.FactoryData);
            }

            if (factory == null)
            {
                factory = NullLoggerFactory.Instance;
            }


            return(factory);
        }
コード例 #27
0
        public override object Read(object untyped, ProtoReader source)
        {
            TDictionary typed = AppendToCollection ? ((TDictionary)untyped) : null;

            //if (typed == null) typed = (TDictionary)Activator.CreateInstance(concreteType);
            if (typed == null)
            {
                typed = (TDictionary)ActivatorUtils.FastCreateInstance(concreteType);
            }

            do
            {
                var          key   = DefaultKey;
                var          value = DefaultValue;
                SubItemToken token = ProtoReader.StartSubItem(source);
                int          field;
                while ((field = source.ReadFieldHeader()) > 0)
                {
                    switch (field)
                    {
                    case 1:
                        key = (TKey)keyTail.Read(null, source);
                        break;

                    case 2:
                        value = (TValue)Tail.Read(Tail.RequiresOldValue ? (object)value : null, source);
                        break;

                    default:
                        source.SkipField();
                        break;
                    }
                }

                ProtoReader.EndSubItem(token, source);
                typed[key] = value;
            } while (source.TryReadFieldHeader(fieldNumber));

            return(typed);
        }
コード例 #28
0
        public static object ParseTuple(Type tupleType, StringSegment value)
        {
            var index = 0;

            Serializer.EatMapStartChar(value, ref index);
            if (JsonTypeSerializer.IsEmptyMap(value, index))
            {
                //return tupleType.CreateInstance();
                return(ActivatorUtils.FastCreateInstance(tupleType));
            }

            var genericArgs = tupleType.GetGenericArguments();
            var argValues   = new object[genericArgs.Length];
            var valueLength = value.Length;

            while (index < valueLength)
            {
                var keyValue = Serializer.EatMapKey(value, ref index);
                Serializer.EatMapKeySeperator(value, ref index);
                var elementValue = Serializer.EatValue(value, ref index);
                if (!keyValue.HasValue)
                {
                    continue;
                }

                var keyIndex = keyValue.Substring("Item".Length).ToInt() - 1;
                var parseFn  = Serializer.GetParseStringSegmentFn(genericArgs[keyIndex]);
                argValues[keyIndex] = parseFn(elementValue);

                Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
            }

            var ctor = tupleType.GetConstructors()
                       .First(x => x.GetParameters().Length == genericArgs.Length);

            return(ctor.Invoke(argValues));
        }
コード例 #29
0
        public static ICollection <T> CreateAndPopulate <T>(Type ofCollectionType, T[] withItems)
        {
            if (withItems == null)
            {
                return(null);
            }

            if (ofCollectionType == null)
            {
                return(new List <T>(withItems));
            }

            var genericType           = ofCollectionType.FirstGenericType();
            var genericTypeDefinition = genericType != null
                ? genericType.GetGenericTypeDefinition()
                : null;

            if (genericTypeDefinition == typeof(HashSet <>))
            {
                return(new HashSet <T>(withItems));
            }

            if (genericTypeDefinition == typeof(LinkedList <>))
            {
                return(new LinkedList <T>(withItems));
            }

            //var collection = (ICollection<T>)ofCollectionType.CreateInstance();
            var collection = ActivatorUtils.FastCreateInstance <ICollection <T> >(ofCollectionType);

            foreach (var item in withItems)
            {
                collection.Add(item);
            }
            return(collection);
        }
コード例 #30
0
        public static Expression GetNewExpression(Type type)
        {
            if (type.IsValueType)
            {
                var x       = Expression.Constant(ActivatorUtils.FastCreateInstance(type));
                var convert = Expression.Convert(x, typeof(object));
                return(convert);
            }
//#if SERIALIZATION
            var defaultCtor        = type.GetConstructor(new Type[] { });
            var il                 = defaultCtor?.GetMethodBody()?.GetILAsByteArray();
            var sideEffectFreeCtor = il != null && il.Length <= 8; //this is the size of an empty ctor

            if (sideEffectFreeCtor)
            {
                //the ctor exists and the size is empty. lets use the New operator
                return(Expression.New(defaultCtor));
            }
//#endif
            var emptyObjectMethod = typeof(TypeEx).GetMethod(nameof(TypeEx.GetEmptyObject));
            var emptyObject       = Expression.Call(null, emptyObjectMethod, type.ToConstant());

            return(emptyObject);
        }