Example #1
0
        private SmartSqlConfigOptions LoadSmartSqlConfig()
        {
            var configFilePath = Path.Combine(AppContext.BaseDirectory, _sqlMapConfigFilePath);
            var configStream   = new ConfigStream
            {
                Path   = configFilePath,
                Stream = FileLoader.Load(configFilePath)
            };

            using (configStream.Stream)
            {
                XmlSerializer xmlSerializer  = new XmlSerializer(typeof(SmartSqlMapConfig));
                var           smartSqlConfig = xmlSerializer.Deserialize(configStream.Stream) as SmartSqlMapConfig;
                if (smartSqlConfig.TypeHandlers != null)
                {
                    foreach (var typeHandler in smartSqlConfig.TypeHandlers)
                    {
                        typeHandler.Handler = TypeHandlerFactory.Create(typeHandler.Type);
                    }
                }

                return(new SmartSqlConfigOptions()
                {
                    Settings = smartSqlConfig.Settings,
                    SmartSqlMaps = smartSqlConfig.SmartSqlMapSources,
                    TypeHandlers = smartSqlConfig.TypeHandlers
                });
            }
        }
        private ITypeHandler ResolveTypeHandler(TypeHandlerFactory typeHandlerFactory, Type parameterClassType, string propertyName, string propertyType, string dbType)
        {
            if (parameterClassType == null)
            {
                return(typeHandlerFactory.GetUnkownTypeHandler());
            }
            if (typeof(IDictionary).IsAssignableFrom(parameterClassType))
            {
                if ((propertyType == null) || (propertyType.Length == 0))
                {
                    return(typeHandlerFactory.GetUnkownTypeHandler());
                }
                try
                {
                    Type type = TypeUtils.ResolveType(propertyType);
                    return(typeHandlerFactory.GetTypeHandler(type, dbType));
                }
                catch (Exception exception)
                {
                    throw new ConfigurationException("Error. Could not set TypeHandler.  Cause: " + exception.Message, exception);
                }
            }
            if (typeHandlerFactory.GetTypeHandler(parameterClassType, dbType) != null)
            {
                return(typeHandlerFactory.GetTypeHandler(parameterClassType, dbType));
            }
            Type memberTypeForGetter = ObjectProbe.GetMemberTypeForGetter(parameterClassType, propertyName);

            return(typeHandlerFactory.GetTypeHandler(memberTypeForGetter, dbType));
        }
Example #3
0
        private T create <T>(DataRow dr, List <ResultCmd> cmds)
        {
            T t = Activator.CreateInstance <T>();

            foreach (ResultCmd c in cmds)
            {
                PropertyInfo pi;
                try
                {
                    pi = typeof(T).GetProperty(c.Property);
                }
                catch (Exception)
                {
                    throw new Exception(String.Format("{0} 对象没有属性 {1}", typeof(T).ToString(), c.Property));
                }
                ITypeHandler typeHandler = c.TypeHandler;
                if (typeHandler == null)
                {
                    typeHandler = TypeHandlerFactory.get(pi.PropertyType);
                }
                if (typeHandler != null)
                {
                    PropertyUtil.setValue(t, pi, typeHandler.getResult(dr, c.ColumnName));
                }
            }
            return(t);
        }
Example #4
0
 public PrepareStatementMiddleware(SmartSqlConfig smartSqlConfig)
 {
     _logger             = smartSqlConfig.LoggerFactory.CreateLogger <PrepareStatementMiddleware>();
     _sqlParamAnalyzer   = smartSqlConfig.SqlParamAnalyzer;
     _dbProviderFactory  = smartSqlConfig.Database.DbProvider.Factory;
     _typeHandlerFactory = smartSqlConfig.TypeHandlerFactory;
 }
Example #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ResultMap"/> class.
        /// </summary>
        /// <param name="id">Identifier used to identify the resultMap amongst the others.</param>
        /// <param name="className">The output class name of the resultMap.</param>
        /// <param name="extendMap">The extend result map bame.</param>
        /// <param name="groupBy">The groupBy properties</param>
        /// <param name="keyColumns">The key columns.</param>
        /// <param name="type">The result type.</param>
        /// <param name="dataExchange">The data exchange.</param>
        /// <param name="objectFactory">The object factory.</param>
        /// <param name="typeHandlerFactory">The type handler factory.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="discriminator">The discriminator.</param>
        public ResultMap(
            string id,
            string className,
            string extendMap,
            string groupBy,
            string keyColumns,
            Type type,
            IDataExchange dataExchange,
            IFactory objectFactory,
            TypeHandlerFactory typeHandlerFactory,
            ResultPropertyCollection properties,
            ArgumentPropertyCollection parameters,
            Discriminator discriminator)
        {
            Contract.Require.That(id, Is.Not.Null & Is.Not.Empty).When("retrieving argument id in ResultMap constructor");
            Contract.Require.That(className, Is.Not.Null & Is.Not.Empty).When("retrieving argument className in ResultMap constructor");
            Contract.Require.That(type, Is.Not.Null).When("retrieving argument type in ResultMap constructor");
            Contract.Require.That(typeHandlerFactory, Is.Not.Null).When("retrieving argument typeHandlerFactory in ResultMap constructor");

            nullResultMap = new NullResultMap();

            this.id            = id;
            this.className     = className;
            this.extendMap     = extendMap;
            this.type          = type;
            this.dataExchange  = dataExchange;
            this.properties    = properties;
            this.parameters    = parameters;
            this.discriminator = discriminator;
            this.objectFactory = objectFactory;
            isSimpleType       = typeHandlerFactory.IsSimpleType(type);

            //对groupBy属性值的处理
            if (!string.IsNullOrEmpty(groupBy))
            {
                string[] props = groupBy.Split(',');
                for (int i = 0; i < props.Length; i++)
                {
                    string memberName = props[i].Trim();
                    groupByPropertyNames.Add(memberName);
                }
                //完成对groupByProperties的初始化
                InitializeGroupByProperties();
                CheckGroupBy();
            }
            //对keyColumns属性值的处理
            if (!string.IsNullOrEmpty(keyColumns))
            {
                string[] columns = keyColumns.Split(',');
                for (int i = 0; i < columns.Length; i++)
                {
                    string column = columns[i].Trim();
                    keyPropertyNames.Add(column);
                }

                InitializeKeysProperties();
                CheckKeysProperties();
            }
        }
Example #6
0
 public override void SetupSmartSql(SmartSqlBuilder smartSqlBuilder)
 {
     InitFilters(smartSqlBuilder);
     _logger             = smartSqlBuilder.SmartSqlConfig.LoggerFactory.CreateLogger <PrepareStatementMiddleware>();
     _sqlParamAnalyzer   = smartSqlBuilder.SmartSqlConfig.SqlParamAnalyzer;
     _dbProviderFactory  = smartSqlBuilder.SmartSqlConfig.Database.DbProvider.Factory;
     _typeHandlerFactory = smartSqlBuilder.SmartSqlConfig.TypeHandlerFactory;
 }
        /// <summary>
        /// Returns a <em>short</em> value read from configuration file.
        /// </summary>
        /// <param name="propertyName">Property name.</param>
        /// <returns>
        /// A <em>short</em> value if the property is found in the configuration, null otherwise.
        /// </returns>
        public short GetShortProperty(String propertyName)
        {
            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName",
                                                "The parameter [propertyName] cannot be null.  Unable to get property value.");
            }

            return((short)TypeHandlerFactory.GetInstance().GetTypeHandler(typeof(short)).ToObject(GetProperty(propertyName)));
        }
Example #8
0
 private ITypeHandler getTypeHandler(Dictionary <String, ITypeHandler> typeHanlders, String propName, Type type)
 {
     if (typeHanlders != null || typeHanlders.Count > 1)
     {
         try
         {
             return(typeHanlders[propName]);
         }
         catch (Exception) { }
     }
     return(TypeHandlerFactory.get(type));
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DataExchangeFactory"/> class.
        /// </summary>
        /// <param name="typeHandlerFactory">The type handler factory.</param>
        /// <param name="objectFactory">The object factory.</param>
        /// <param name="accessorFactory">The accessor factory.</param>
        public DataExchangeFactory(TypeHandlerFactory typeHandlerFactory,
                                   IObjectFactory objectFactory,
                                   AccessorFactory accessorFactory)
        {
            _objectFactory      = objectFactory;
            _typeHandlerFactory = typeHandlerFactory;
            _accessorFactory    = accessorFactory;

            _primitiveDataExchange  = new PrimitiveDataExchange(this);
            _complexDataExchange    = new ComplexDataExchange(this);
            _listDataExchange       = new ListDataExchange(this);
            _dictionaryDataExchange = new DictionaryDataExchange(this);
        }
        /// <summary>
        /// Sets a <em>System.Boolean</em> property in the configuration.
        /// </summary>
        /// <param name="propertyName">Name of the property to set.</param>
        /// <param name="propertyValue">Property value.</param>
        public void SetBooleanProperty(String propertyName, Boolean propertyValue)
        {
            if (!_Writable)
            {
                throw new InvalidOperationException(String.Format("The configuration [{0}] is not writable.  Cannot set property value.", _Name));
            }

            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName",
                                                "The parameter [propertyName] cannot be null.  Unable to set property value.");
            }

            SetProperty(propertyName, TypeHandlerFactory.GetInstance().GetTypeHandler(typeof(Boolean)).ToString(propertyValue));
        }
        /// <summary>
        /// Returns a <em>System.Boolean</em> value read from configuration file.
        /// </summary>
        /// <param name="propertyName">Property name.</param>
        /// <returns>
        /// A <em>System.Boolean</em> value if the property is found in the configuration, false otherwise.
        /// </returns>
        public Boolean GetBooleanProperty(String propertyName)
        {
            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName",
                                                "The parameter [propertyName] cannot be null.  Unable to get property value.");
            }

            String propertyValue = GetProperty(propertyName);

            if (propertyValue != null)
            {
                return((Boolean)TypeHandlerFactory.GetInstance().GetTypeHandler(typeof(Boolean)).ToObject(propertyValue));
            }

            return(false);
        }
Example #12
0
 public SmartSqlMapConfig LoadConfig(ConfigStream configStream)
 {
     using (configStream.Stream)
     {
         XmlSerializer xmlSerializer = new XmlSerializer(typeof(SmartSqlMapConfig));
         SqlMapConfig              = xmlSerializer.Deserialize(configStream.Stream) as SmartSqlMapConfig;
         SqlMapConfig.Path         = configStream.Path;
         SqlMapConfig.SmartSqlMaps = new Dictionary <String, SmartSqlMap> {
         };
         if (SqlMapConfig.TypeHandlers != null)
         {
             foreach (var typeHandler in SqlMapConfig.TypeHandlers)
             {
                 typeHandler.Handler = TypeHandlerFactory.Create(typeHandler.Type);
             }
         }
         return(SqlMapConfig);
     }
 }
Example #13
0
        /// <summary>
        /// Resolve TypeHandler
        /// </summary>
        /// <param name="parameterClassType"></param>
        /// <param name="propertyName"></param>
        /// <param name="propertyType"></param>
        /// <param name="dbType"></param>
        /// <param name="typeHandlerFactory"></param>
        /// <returns></returns>
        private ITypeHandler ResolveTypeHandler(TypeHandlerFactory typeHandlerFactory,
                                                Type parameterClassType, string propertyName,
                                                string propertyType, string dbType)
        {
            ITypeHandler handler = null;

            if (parameterClassType == null)
            {
                handler = typeHandlerFactory.GetUnkownTypeHandler();
            }
            else if (typeof(IDictionary).IsAssignableFrom(parameterClassType))
            {
                if (propertyType == null || propertyType.Length == 0)
                {
                    handler = typeHandlerFactory.GetUnkownTypeHandler();
                }
                else
                {
                    try
                    {
                        Type typeClass = TypeUtils.ResolveType(propertyType);
                        handler = typeHandlerFactory.GetTypeHandler(typeClass, dbType);
                    }
                    catch (Exception e)
                    {
                        throw new ConfigurationException("Error. Could not set TypeHandler.  Cause: " + e.Message, e);
                    }
                }
            }
            else if (typeHandlerFactory.GetTypeHandler(parameterClassType, dbType) != null)
            {
                handler = typeHandlerFactory.GetTypeHandler(parameterClassType, dbType);
            }
            else
            {
                Type typeClass = ObjectProbe.GetMemberTypeForGetter(parameterClassType, propertyName);
                handler = typeHandlerFactory.GetTypeHandler(typeClass, dbType);
            }

            return(handler);
        }
 protected BaseUmbracoContext()
 {
     _typeHandlerFactory = TypeHandlerFactory.Instance;
     _cacheManager       = new CacheManager();
 }
        /// <summary>
        /// Builds the the MyBatis core model (statement, alias, resultMap, parameterMap, dataSource)
        /// from an <see cref="IConfigurationStore"/> and store all the refrences in an <see cref="IModelStore"/> .
        /// </summary>
        /// <param name="configurationSetting">The configuration setting.</param>
        /// <param name="store">The configuration store.</param>
        /// <returns>The model store</returns>
        public virtual void BuildModel(ConfigurationSetting configurationSetting, IConfigurationStore store)
        {
            IObjectFactory      objectFactory      = null;
            IGetAccessorFactory getAccessorFactory = null;
            ISetAccessorFactory setAccessorFactory = null;
            ISessionFactory     sessionFactory     = null;
            ISessionStore       sessionStore       = null;

            if (configurationSetting != null)
            {
                objectFactory          = configurationSetting.ObjectFactory;
                setAccessorFactory     = configurationSetting.SetAccessorFactory;
                getAccessorFactory     = configurationSetting.GetAccessorFactory;
                dataSource             = configurationSetting.DataSource;
                sessionFactory         = configurationSetting.SessionFactory;
                sessionStore           = configurationSetting.SessionStore;
                dynamicSqlEngine       = configurationSetting.DynamicSqlEngine;
                isCacheModelsEnabled   = configurationSetting.IsCacheModelsEnabled;
                useStatementNamespaces = configurationSetting.UseStatementNamespaces;
                useReflectionOptimizer = configurationSetting.UseReflectionOptimizer;
                preserveWhitespace     = configurationSetting.PreserveWhitespace;
            }

            // Xml setting override code setting
            LoadSetting(store);

            if (objectFactory == null)
            {
                objectFactory = new ObjectFactory(useReflectionOptimizer);
            }
            if (setAccessorFactory == null)
            {
                setAccessorFactory = new SetAccessorFactory(useReflectionOptimizer);
            }
            if (getAccessorFactory == null)
            {
                getAccessorFactory = new GetAccessorFactory(useReflectionOptimizer);
            }
            AccessorFactory accessorFactory = new AccessorFactory(setAccessorFactory, getAccessorFactory);

            TypeHandlerFactory typeHandlerFactory = new TypeHandlerFactory();
            TypeAlias          alias = new TypeAlias("MEMORY", typeof(PerpetualCache));

            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("Perpetual", typeof(PerpetualCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("LRU", typeof(LruCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("Lru", typeof(LruCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("FIFO", typeof(FifoCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("Fifo", typeof(FifoCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("Weak", typeof(WeakCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("WEAK", typeof(WeakCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("AnsiStringTypeHandler", typeof(AnsiStringTypeHandler));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            modelStore.DataExchangeFactory = new DataExchangeFactory(typeHandlerFactory, objectFactory, accessorFactory);

            if (sessionStore == null)
            {
                sessionStore = SessionStoreFactory.GetSessionStore(modelStore.Id);
            }
            modelStore.SessionStore = sessionStore;

            deSerializerFactory = new DeSerializerFactory(modelStore);

            ParameterMap emptyParameterMap = new ParameterMap(
                ConfigConstants.EMPTY_PARAMETER_MAP,
                string.Empty,
                string.Empty,
                typeof(string),
                modelStore.DataExchangeFactory.GetDataExchangeForClass(null),
                false);

            modelStore.AddParameterMap(emptyParameterMap);

            BuildProviders(store);
            BuildDataSource(store);

            if (sessionFactory == null)
            {
                sessionFactory = new DefaultSessionFactory(
                    dataSource,
                    modelStore.SessionStore,
                    new DefaultTransactionManager(new AdoTransactionFactory()));
            }
            modelStore.SessionFactory = sessionFactory;

            BuildTypeAlias(store);
            BuildTypeHandlers(store);
            BuildCacheModels(store);
            BuildResultMaps(store);

            for (int i = 0; i < nestedProperties.Count; i++)
            {
                ResultProperty property = nestedProperties[i];
                property.NestedResultMap = modelStore.GetResultMap(property.NestedResultMapName);
            }

            for (int i = 0; i < discriminators.Count; i++)
            {
                discriminators[i].Initialize(modelStore);
            }
            BuildParameterMaps(store);
            BuildMappedStatements(store, configurationSetting);

            for (int i = 0; i < store.CacheModels.Length; i++)
            {
                CacheModel cacheModel = modelStore.GetCacheModel(store.CacheModels[i].Id);

                for (int j = 0; j < cacheModel.StatementFlushNames.Count; j++)
                {
                    string           statement       = cacheModel.StatementFlushNames[j];
                    IMappedStatement mappedStatement = modelStore.GetMappedStatement(statement);
                    if (mappedStatement != null)
                    {
                        cacheModel.RegisterTriggerStatement(mappedStatement);
                        if (logger.IsDebugEnabled)
                        {
                            logger.Debug("Registering trigger statement [" + statement + "] to cache model [" + cacheModel.Id + "]");
                        }
                    }
                    else
                    {
                        if (logger.IsWarnEnabled)
                        {
                            logger.Warn("Unable to register trigger statement [" + statement + "] to cache model [" + cacheModel.Id + "]. Statement does not exist.");
                        }
                    }
                }
            }

            if (logger.IsInfoEnabled)
            {
                logger.Info("Model Store");
                logger.Info(modelStore.ToString());
            }
        }
 /// <summary>
 /// Initialize a the result property
 /// for AutoMapper
 /// </summary>
 /// <param name="setAccessor">An <see cref="ISetAccessor"/>.</param>
 /// <param name="typeHandlerFactory"></param>
 internal void Initialize(TypeHandlerFactory typeHandlerFactory, ISetAccessor setAccessor)
 {
     _setAccessor = setAccessor;
     _typeHandler = typeHandlerFactory.GetTypeHandler(setAccessor.MemberType);
 }
Example #17
0
        public override SmartSqlMapConfig Load()
        {
            SqlMapConfig = new SmartSqlMapConfig()
            {
                SmartSqlMaps       = new Dictionary <String, SmartSqlMap>(),
                SmartSqlMapSources = _options.SmartSqlMaps,
                Database           = new Configuration.Database()
                {
                    DbProvider      = _options.Database.DbProvider,
                    WriteDataSource = _options.Database.Write,
                    ReadDataSources = _options.Database.Read
                },
                Settings     = _options.Settings,
                TypeHandlers = _options.TypeHandlers,
            };
            if (SqlMapConfig.TypeHandlers != null)
            {
                foreach (var typeHandler in SqlMapConfig.TypeHandlers)
                {
                    typeHandler.Handler = TypeHandlerFactory.Create(typeHandler.Type);
                }
            }
            foreach (var sqlMapSource in SqlMapConfig.SmartSqlMapSources)
            {
                switch (sqlMapSource.Type)
                {
                case SmartSqlMapSource.ResourceType.File:
                {
                    LoadSmartSqlMap(SqlMapConfig, sqlMapSource.Path);
                    break;
                }

                case SmartSqlMapSource.ResourceType.Directory:
                case SmartSqlMapSource.ResourceType.DirectoryWithAllSub:
                {
                    SearchOption searchOption = SearchOption.TopDirectoryOnly;
                    if (sqlMapSource.Type == SmartSqlMapSource.ResourceType.DirectoryWithAllSub)
                    {
                        searchOption = SearchOption.AllDirectories;
                    }
                    var dicPath            = Path.Combine(AppContext.BaseDirectory, sqlMapSource.Path);
                    var childSqlmapSources = Directory.EnumerateFiles(dicPath, "*.xml", searchOption);
                    foreach (var childSqlmapSource in childSqlmapSources)
                    {
                        LoadSmartSqlMap(SqlMapConfig, childSqlmapSource);
                    }
                    break;
                }

                default:
                {
                    if (_logger.IsEnabled(LogLevel.Debug))
                    {
                        _logger.LogDebug($"OptionConfigLoader unknow SmartSqlMapSource.ResourceType:{sqlMapSource.Type}.");
                    }
                    break;
                }
                }
            }
            InitDependency();
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"OptionConfigLoader Load End");
            }

            if (SqlMapConfig.Settings.IsWatchConfigFile)
            {
                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug($"OptionConfigLoader Load Add WatchConfig Starting.");
                }
                WatchConfig(SqlMapConfig);
                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug($"OptionConfigLoader Load Add WatchConfig End.");
                }
            }
            return(SqlMapConfig);
        }
 /// <summary>
 /// Register a type converter with the DefaultConverterFactory.
 /// </summary>
 /// <param name="forType">the type to register</param>
 /// <param name="converter">the converter</param>
 public void RegisterTypeConverter(Type forType, IJsonTypeConverter converter)
 {
     TypeHandlerFactory.RegisterTypeConverter(forType, converter);
 }
 /// <summary>
 /// Register a type converter with the DefaultConverterFactory.
 /// </summary>
 /// <param name="forType">the property to register</param>
 /// <param name="converter">the converter</param>
 public void RegisterTypeConverter(Type forType, string propertyName, IJsonTypeConverter converter)
 {
     TypeHandlerFactory.RegisterTypeConverter(forType, propertyName, converter);
 }
Example #20
0
        /// <summary>
        /// Builds the the iBATIS core model (statement, alias, resultMap, parameterMap, dataSource)
        /// from an <see cref="IConfigurationStore"/> and store all the refrences in an <see cref="IModelStore"/> .
        /// </summary>
        /// <param name="configurationSetting">The configuration setting.</param>
        /// <param name="store">The configuration store.</param>
        /// <returns>The model store</returns>
        public virtual void BuildModel(ConfigurationSetting configurationSetting, IConfigurationStore store)
        {
            IObjectFactory      objectFactory      = null;
            IGetAccessorFactory getAccessorFactory = null;
            ISetAccessorFactory setAccessorFactory = null;
            ISessionFactory     sessionFactory     = null;
            ISessionStore       sessionStore       = null;

            if (configurationSetting != null)
            {
                objectFactory          = configurationSetting.ObjectFactory;
                setAccessorFactory     = configurationSetting.SetAccessorFactory;
                getAccessorFactory     = configurationSetting.GetAccessorFactory;
                dataSource             = configurationSetting.DataSource;
                sessionFactory         = configurationSetting.SessionFactory;
                sessionStore           = configurationSetting.SessionStore;
                dynamicSqlEngine       = configurationSetting.DynamicSqlEngine;
                isCacheModelsEnabled   = configurationSetting.IsCacheModelsEnabled;
                useStatementNamespaces = configurationSetting.UseStatementNamespaces;
                useReflectionOptimizer = configurationSetting.UseReflectionOptimizer;
                preserveWhitespace     = configurationSetting.PreserveWhitespace;
            }

            // Xml setting override code setting
            //取store中的数据初始化类成员 为下面做准备
            LoadSetting(store);

            if (objectFactory == null)
            {
                objectFactory = new ObjectFactory(useReflectionOptimizer);
            }
            if (setAccessorFactory == null)
            {
                setAccessorFactory = new SetAccessorFactory(useReflectionOptimizer);
            }
            if (getAccessorFactory == null)
            {
                getAccessorFactory = new GetAccessorFactory(useReflectionOptimizer);
            }
            AccessorFactory accessorFactory = new AccessorFactory(setAccessorFactory, getAccessorFactory);

            TypeHandlerFactory typeHandlerFactory = new TypeHandlerFactory();
            TypeAlias          alias = new TypeAlias("MEMORY", typeof(PerpetualCache));

            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("Perpetual", typeof(PerpetualCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("LRU", typeof(LruCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("Lru", typeof(LruCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("FIFO", typeof(FifoCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("Fifo", typeof(FifoCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("Weak", typeof(WeakCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("WEAK", typeof(WeakCache));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("MemCached", typeof(MemCached));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);
            alias = new TypeAlias("MEMCACHED", typeof(MemCached));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            alias = new TypeAlias("AnsiStringTypeHandler", typeof(AnsiStringTypeHandler));
            typeHandlerFactory.AddTypeAlias(alias.Id, alias);

            //将以上类信息存入到modelStore中 实质性工作
            modelStore.DataExchangeFactory = new DataExchangeFactory(typeHandlerFactory, objectFactory, accessorFactory);

            if (sessionStore == null)
            {
                sessionStore = SessionStoreFactory.GetSessionStore(modelStore.Id);
            }
            //将ISessionStore类对象存入modelStore中 准备数据库的连接 与 事物操作功能  实质性工作
            modelStore.SessionStore = sessionStore;

            //初始化DefaultModelBuilder的成员变量
            deSerializerFactory = new DeSerializerFactory(modelStore);

            //设置一个空类型的参数映射类
            ParameterMap emptyParameterMap = new ParameterMap(
                ConfigConstants.EMPTY_PARAMETER_MAP,
                string.Empty,
                string.Empty,
                typeof(string),
                modelStore.DataExchangeFactory.GetDataExchangeForClass(null), //获得ComplexDataExchange对象
                false);

            //向参数字典中添加一个空参数类
            modelStore.AddParameterMap(emptyParameterMap);

            //完成了对DefaultModelBuilder成员变量dbProviderFactory的初始化,其中完成了对provider使用中节点的类初始化
            BuildProviders(store);

            //完成了对DefaultModelBuilder成员变量IDataSource的初始化,包括数据库的名字 连接字符串 以及DbPrivder类
            BuildDataSource(store);

            if (sessionFactory == null)
            {
                sessionFactory = new DefaultSessionFactory(
                    dataSource,
                    modelStore.SessionStore,
                    new DefaultTransactionManager(new AdoTransactionFactory()));
            }
            //初始化modelStore中的ISessionFactory变量
            modelStore.SessionFactory = sessionFactory;

            //将具体SQLXML配置文件中的Alias节点对应的别名信息写入到modelStore中的TypeHandlerFactory的字典中
            BuildTypeAlias(store);

            //将TypeHanders下的子节点信息放入 modelStore.DataExchangeFactory.TypeHandlerFactory中的字典当中
            BuildTypeHandlers(store);

            //将cacheModels下子节点cacheModel加入到modelStore的CacheModel字典中
            BuildCacheModels(store);
            //将resultMap节点信息添加到modelStore的resultMaps中
            BuildResultMaps(store);

            //为resultMapping属性所在的节点信息类设置对应的ResultProperty
            for (int i = 0; i < nestedProperties.Count; i++)
            {
                ResultProperty property = nestedProperties[i];
                property.NestedResultMap = modelStore.GetResultMap(property.NestedResultMapName);
            }

            for (int i = 0; i < discriminators.Count; i++)
            {
                //完成对discriminator类中对字典的初始化
                discriminators[i].Initialize(modelStore);
            }
            //将parameter节点信息添加到modelStore类中的parameterMaps字典中
            BuildParameterMaps(store);

            //将statements下的节点添加到modelStore的statements的字典中
            BuildMappedStatements(store, configurationSetting);

            for (int i = 0; i < store.CacheModels.Length; i++)
            {
                CacheModel cacheModel = modelStore.GetCacheModel(store.CacheModels[i].Id);

                for (int j = 0; j < cacheModel.StatementFlushNames.Count; j++)
                {
                    string           statement       = cacheModel.StatementFlushNames[j];
                    IMappedStatement mappedStatement = modelStore.GetMappedStatement(statement);
                    if (mappedStatement != null)
                    {
                        //为IMappedStatement类的Executed制定委托事件  目的是清空缓存
                        cacheModel.RegisterTriggerStatement(mappedStatement);
                        if (logger.IsDebugEnabled)
                        {
                            logger.Debug("Registering trigger statement [" + statement + "] to cache model [" + cacheModel.Id + "]");
                        }
                    }
                    else
                    {
                        if (logger.IsWarnEnabled)
                        {
                            logger.Warn("Unable to register trigger statement [" + statement + "] to cache model [" + cacheModel.Id + "]. Statement does not exist.");
                        }
                    }
                }
            }

            if (logger.IsInfoEnabled)
            {
                logger.Info("Model Store");
                logger.Info(modelStore.ToString());
            }
        }
Example #21
0
		/// <summary>
		/// Initialize a the result property
		/// for AutoMapper
		/// </summary>
        /// <param name="setAccessor">An <see cref="ISetAccessor"/>.</param>
		/// <param name="typeHandlerFactory"></param>
		internal void Initialize(TypeHandlerFactory typeHandlerFactory, ISetAccessor setAccessor )
		{
            _setAccessor = setAccessor;
            _typeHandler = typeHandlerFactory.GetTypeHandler(setAccessor.MemberType);
		}