Exemplo n.º 1
0
        /// <summary>
        /// Try to generate an InterfaceApplier for the specified interface (the typeparam MUST be an interface, not a class)
        /// </summary>
        /// <typeparam name="T">This will always be an interface, never a class</typeparam>
        public IInterfaceApplier <T> GenerateInterfaceApplier <T>(IReadValueConverter readValueConverter)
        {
            if (!typeof(T).IsInterface)
            {
                throw new ArgumentException("typeparam must be an interface type", "targetInterface");
            }
            if (readValueConverter == null)
            {
                throw new ArgumentNullException("readValueConverter");
            }

            lock (_cache)
            {
                if (_cache.ContainsKey(typeof(T)))
                {
                    return((IInterfaceApplier <T>)_cache[typeof(T)]);
                }
            }
            var interfaceApplier = _interfaceApplierFactory.GenerateInterfaceApplier <T>(readValueConverter);

            lock (_cache)
            {
                if (!_cache.ContainsKey(typeof(T)))
                {
                    _cache.Add(typeof(T), interfaceApplier);
                }
            }
            return(interfaceApplier);
        }
        private object tryToConvertValueIfRequired(Type targetType, object value)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }

            // If no conversion is required, no work to do
            // - Note: We can only deal with applying interfaces to objects so if a conversion is required where the target is not an interface
            //   then there's nothing we can do here, we'll have to return the value unconverted (likewise, if the target type is an int but
            //   the current value is null, although this is obviously incorrect there's nothing we can do about it here)
            if (!targetType.IsInterface || (value == null) || (value.GetType().IsSubclassOf(targetType)))
            {
                return(value);
            }

            // Do we already have an interface applier available for this type?
            var interfaceApplierExisting = _interfaceAppliers.FirstOrDefault(i => i.TargetType.Equals(targetType));

            if (interfaceApplierExisting != null)
            {
                return(interfaceApplierExisting.Apply(value));
            }

            // Try to generate new interface applier
            var interfaceApplierNew = _interfaceApplierFactory.GenerateInterfaceApplier(targetType, this);

            lock (_writeLock)
            {
                if (!_interfaceAppliers.Any(i => i.TargetType.Equals(targetType)))
                {
                    _interfaceAppliers = _interfaceAppliers.Add(interfaceApplierNew);
                }
            }
            return(interfaceApplierNew.Apply(value));
        }