Esempio n. 1
0
        public IEnumerable <T> BindModel <T>(object source)
        {
            DataTable dt = (DataTable)source;
            IEnumerable <DataColumn> dclist = dt.Columns.Cast <DataColumn>();
            List <T> modellist = new List <T>();

            foreach (DataRow dr in dt.Rows)
            {
                TypeX typex         = TypeX.Create(typeof(T));
                T     modelInstance = (T)typex.CreateInstance();
                //T modelInstance = (T)Activator.CreateInstance(typeof(T));
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    DataColumn dc = dclist.Where(item => string.Compare(property.Name, item.ColumnName, true) == 0).FirstOrDefault();

                    if (null != dc)
                    {
                        PropertyInfoX propx = PropertyInfoX.Create(property);
                        propx.SetValue(modelInstance, dr[dc.ColumnName]);

                        //property.SetValue(modelInstance, Convert.ChangeType(dr[dc.ColumnName], property.PropertyType),null);
                    }
                }
                modellist.Add(modelInstance);
            }

            return(modellist);
        }
Esempio n. 2
0
        public TaskManager()
        {
            var ps = typeof(ITaskJob).GetAllSubclasses();

            _jobPlugins      = ps.Where(e => e.IsClass).Select(e => TypeX.CreateInstance(e) as ITaskJob).ToArray();
            _jobProcessTimer = new Timer[_jobPlugins.Length];
        }
Esempio n. 3
0
        private void btnAddTable_Click(object sender, EventArgs e)
        {
            if (Tables == null || Tables.Count < 1)
            {
                return;
            }

            Type type = Tables[0].GetType();

            if (type == null)
            {
                return;
            }

            IDataTable table = TypeX.CreateInstance(type) as IDataTable;

            if (table == null)
            {
                return;
            }

            Tables.Add(table);
            table.ID          = Tables.Count;
            table.Name        = "NewTable" + table.ID;
            table.Description = "新建表" + table.ID;

            SetTables(Tables, Tables.Count - 1);
        }
Esempio n. 4
0
        public static DriverBase CreateDriver(IConfigurationSource src = null, string typename = TypeName)
        {
            lock (lockobj)
            {
                string driverString;
                string connString;
                try
                {
                    if (db != null)
                    {
                        return(db);
                    }

                    if (Starter.Properties == null)
                    {
                        Starter.Initialize(typename, src);
                    }
                    Starter.Properties.TryGetValue(Environment.ConnectionDriver, out driverString);
                    Starter.Properties.TryGetValue(Environment.ConnectionString, out connString);

                    TypeX typex = TypeX.Create(ReflectHelper.ClassForName(driverString));
                    db = (DriverBase)typex.CreateInstance();
                    //db = (DriverBase)Activator.CreateInstance(ReflectHelper.ClassForName(driverString));
                    db.ConnString = connString;
                    return(db);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Esempio n. 5
0
File: SqlCe.cs Progetto: rebider/soa
        public static SqlCeEngine Create(String connstr)
        {
            if (EngineType == null)
            {
                return(null);
            }
            if (String.IsNullOrEmpty(connstr))
            {
                return(null);
            }

            try
            {
                var e = TypeX.CreateInstance(EngineType, connstr);
                if (e == null)
                {
                    return(null);
                }

                var sce = new SqlCeEngine();
                sce.Engine = e;
                return(sce);
            }
            catch { return(null); }
        }
Esempio n. 6
0
 /// <summary>根据名称获取默认提供者</summary>
 /// <param name="dbType"></param>
 /// <returns></returns>
 internal static IDatabase GetDefault(Type dbType)
 {
     if (dbType == null)
     {
         return(null);
     }
     return(defaultDbs2.GetItem(dbType, dt => (IDatabase)TypeX.CreateInstance(dt)));
 }
Esempio n. 7
0
        private void StartAttachServers()
        {
            var dic = Config.GetConfigByPrefix("XAgent.AttachServer.");

            if (dic != null && dic.Count > 0)
            {
                // 实例化
                foreach (var item in dic)
                {
                    if (!item.Key.IsNullOrWhiteSpace() && !item.Value.IsNullOrWhiteSpace())
                    {
                        WriteLine("");
                        WriteLine("正在加载:{0} = {1}", item.Key, item.Value);
                        var type = TypeX.GetType(item.Value, true);
                        if (type != null)
                        {
                            var service = TypeX.CreateInstance(type) as IServer;
                            if (service != null)
                            {
                                AttachServers[item.Key] = service;
                            }
                        }
                    }
                }

                // 加载配置。【服务名.属性】的配置方式
                foreach (var item in AttachServers)
                {
                    if (item.Value != null)
                    {
                        var type = item.Value.GetType();
                        // 遍历所有属性,查找指定的设置项
                        foreach (var pi in type.GetProperties(true))
                        {
                            var    name  = String.Format("XAgent.{0}.{1}", item.Key, pi.Name);
                            Object value = null;
                            // 读取配置,并赋值
                            if (Config.TryGetConfig(name, pi.PropertyType, out value))
                            {
                                WriteLine("配置:{0} = {1}", name, value);
                                //PropertyInfoX.Create(pi).SetValue(item.Value, value);
                                item.Value.SetValue(pi, value);
                            }
                        }
                    }
                }

                // 启动
                foreach (var item in AttachServers)
                {
                    if (item.Value != null)
                    {
                        WriteLine("启动:{0}", item.Key);
                        item.Value.Start();
                    }
                }
            }
        }
Esempio n. 8
0
        /// <summary>创建实例</summary>
        /// <returns></returns>
        protected virtual T Create()
        {
            if (OnCreate != null)
            {
                return(OnCreate());
            }

            return((T)TypeX.CreateInstance(typeof(T)));
        }
Esempio n. 9
0
        /// <summary>从数据读写器加载数据。无数据时返回空集合而不是null。</summary>
        /// <param name="dr">数据读写器</param>
        /// <returns>实体数组</returns>
        public IEntityList LoadData(IDataReader dr)
        {
            //if (dr == null) return null;

            //// 先移到第一行,要取字段名等信息
            //if (!dr.Read()) return null;

            // 准备好实体列表
            IEntityList list = TypeX.CreateInstance(typeof(EntityList <>).MakeGenericType(EntityType)) as IEntityList;

            if (dr == null)
            {
                return(list);
            }

            // 先移到第一行,要取字段名等信息
            if (!dr.Read())
            {
                return(list);
            }

            List <FieldItem> ps   = new List <FieldItem>();
            List <String>    exts = new List <String>();

            for (int i = 0; i < dr.FieldCount; i++)
            {
                String    name = dr.GetName(i);
                FieldItem fi   = null;
                if (FieldItems.TryGetValue(name, out fi))
                {
                    ps.Add(fi);
                }
                else
                {
                    exts.Add(name);
                }
            }

            // 遍历每一行数据,填充成为实体
            do
            {
                // 由实体操作者创建实体对象,因为实体操作者可能更换
                IEntity entity = Factory.Create();
                foreach (FieldItem item in ps)
                {
                    SetValue(entity, item.Name, item.Type, dr[item]);
                }

                foreach (String item in exts)
                {
                    SetValue(entity, item, null, dr[item]);
                }

                list.Add(entity);
            } while (dr.Read());
            return(list);
        }
Esempio n. 10
0
        private static IObjectContainer Reg <T>(this IObjectContainer container, Object id = null)
        {
            IDatabase db = TypeX.CreateInstance(typeof(T)) as IDatabase;

            if (id == null)
            {
                id = db.DbType;
            }

            // 把这个实例注册进去,作为默认实现
            return(container.Register(typeof(IDatabase), null, db, id));
        }
Esempio n. 11
0
        /// <summary>读取实现了可序列化接口的对象</summary>
        /// <param name="type">要读取的对象类型</param>
        /// <param name="value">要读取的对象</param>
        /// <param name="callback">处理成员的方法</param>
        /// <returns>是否读取成功</returns>
        public override bool ReadSerializable(Type type, ref object value, ReadObjectCallback callback)
        {
            if (!typeof(IXmlSerializable).IsAssignableFrom(type))
            {
                return(base.ReadSerializable(type, ref value, callback));
            }

            if (value == null)
            {
                value = TypeX.CreateInstance(type);
            }
            ((IXmlSerializable)value).ReadXml(Reader);
            return(true);
        }
Esempio n. 12
0
        /// <summary>加载插件。此时是加载所有插件,无法识别哪些是需要的</summary>
        public void Load()
        {
            var list = new List <IPlugin>();

            // 此时是加载所有插件,无法识别哪些是需要的
            foreach (var item in LoadPlugins())
            {
                if (item != null)
                {
                    list.Add(TypeX.CreateInstance(item) as IPlugin);
                }
            }
            _Plugins = list;
        }
Esempio n. 13
0
 static MallPluginProvider()
 {
     //try
     //{
     //    _sp = (MallPluginBase)Activator.CreateInstance(Type.GetType("BBX.Mall.MallPlugin, BBX.Mall", false, true));
     //}
     //catch
     //{
     //    _sp = null;
     //}
     foreach (var item in AssemblyX.FindAllPlugins(typeof(MallPluginBase), true))
     {
         _sp = TypeX.CreateInstance(item) as MallPluginBase;
         break;
     }
 }
Esempio n. 14
0
        /// <summary>
        ///     从流中读取消息
        /// </summary>
        /// <param name="stream">
        /// </param>
        /// <returns>
        ///     The <see cref="EntityBase" />.
        /// </returns>
        public static TtsEntity Read(Stream stream)
        {
            var ms    = stream;
            var start = ms.Position;

            ms.Position = 0;

            // 读取命令码
            var function = (TtsFunction)ms.ReadByte();
            // 读取了响应类型和消息类型后,动态创建消息对象
            var type   = ObjectContainer.Current.ResolveType <IResponse>(function);
            var entity = TypeX.CreateInstance(type) as TtsEntity;

            entity.Function = function;
            return(entity);
        }
Esempio n. 15
0
 static SpacePluginProvider()
 {
     //try
     //{
     //    _sp = (SpacePluginBase)Activator.CreateInstance(Type.GetType("Discuz.Space.SpacePlugin, Discuz.Space", false, true));
     //}
     //catch
     //{
     //    _sp = null;
     //}
     foreach (var item in AssemblyX.FindAllPlugins(typeof(SpacePluginBase), true))
     {
         _sp = TypeX.CreateInstance(item) as SpacePluginBase;
         break;
     }
 }
Esempio n. 16
0
        /// <summary>尝试读取枚举</summary>
        /// <remarks>重点和难点在于如果得知枚举元素类型,这里假设所有元素类型一致,否则实在无法处理</remarks>
        /// <param name="type">要读取的对象类型</param>
        /// <param name="value">要读取的对象</param>
        /// <param name="callback">处理成员的方法</param>
        /// <returns>是否读取成功</returns>
        public override bool ReadEnumerable(Type type, ref object value, ReadObjectCallback callback)
        {
            Type t = type.GetElementType();

            #region 锯齿二维数组处理
            Int32 length = 1;
            while (typeof(IEnumerable).IsAssignableFrom(t))
            {
                length++;
                t = t.GetElementType();
            }

            if (length > 1)
            {
                Array array = TypeX.CreateInstance(type, length) as Array;
                t = type.GetElementType();
                for (int j = 0; j < length - 1; j++)
                {
                    //开始循环之前已赋值,所以第一次循环时跳过
                    if (j > 0)
                    {
                        t = t.GetElementType();
                    }

                    for (int i = 0; i < array.Length; i++)
                    {
                        if (value != null)
                        {
                            value = null;
                        }
                        if (base.ReadEnumerable(t, ref value, callback) && value != null)
                        {
                            array.SetValue(value, i);
                        }
                    }
                }
                if (array != null && array.Length > 0)
                {
                    value = array;
                }
                return(true);
            }
            #endregion

            return(base.ReadEnumerable(type, ref value, callback));
        }
Esempio n. 17
0
        /// <summary>
        /// 根据实体名称,获取此实体字段名称的数组List<string>
        /// </summary>
        /// <param name="typeName">完整实体名称, [命名空间.实体名称]</param>
        /// <returns></returns>
        public static List <string> GetEntityFieldList(this string tableName)
        {
            List <string> list = new List <string>();

            tableName = string.Format("{0}.{1}", ConfigHelper.GetAppSettings("EntitySpaceName"), tableName);
            TypeX  EntityType = TypeX.Create(TypeX.GetType(tableName, true));  //根据类的完整名称建立类的类型,用于动态创建类 如: Clump.Mobile.Models.NewsInfo
            Object objEntity  = EntityType.CreateInstance();                   //动态建立类的对象 实体类的对象Object objEntity = EntityType.CreateInstance(true);意思是在创建实体对象时 A a = new A(true)

            PropertyInfo[] props        = objEntity.GetType().GetProperties(); //获取此对象的,字段集合
            object         propertValue = String.Empty;

            foreach (PropertyInfo item in props)
            {
                list.Add(item.Name);
            }
            return(list);
        }
Esempio n. 18
0
        /// <summary>创建实体操作接口</summary>
        /// <remarks>因为只用来做实体操作,所以只需要一个实例即可</remarks>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IEntityOperate CreateOperate(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            // 确保实体类已被初始化,实际上,因为实体类静态构造函数中会注册IEntityOperate,所以下面的委托按理应该再也不会被执行了
            EnsureInit(type);

            return(op_cache.GetItem(type, delegate(Type key)
            {
                Type optype = null;
                if (typeof(IEntityOperate).IsAssignableFrom(key))
                {
                    optype = key;
                }
                else
                {
                    //Type t = GetEntityOperateType();
                    //if (t != null) key = t.MakeGenericType(key);
                    optype = GetEntityOperateType(key);
                }
                if (optype == null || !typeof(IEntityOperate).IsAssignableFrom(optype))
                {
                    throw new XCodeException("无法创建{0}的实体操作接口!", key);
                }

                IEntityOperate op = TypeX.CreateInstance(optype) as IEntityOperate;
                if (op == null)
                {
                    throw new XCodeException("无法创建{0}的实体操作接口!", key);
                }

                // 如果源实体类型实现了IEntity接口,则以它的对象为操作者的默认值
                // 因为可能存在非泛型继承,比如Admin=>Administrator=>Administrator<Administrator>
                if (typeof(IEntity).IsAssignableFrom(key))
                {
                    op.Default = TypeX.CreateInstance(key) as IEntity;
                }

                return op;
            }));
        }
Esempio n. 19
0
        /// <summary>获取某个类型的默认对象</summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Object GetDefaultObject(Type type)
        {
            // 使用FormatterServices.GetSafeUninitializedObject创建对象,该方法创建的对象不执行构造函数
            return(defCache.GetItem(type, delegate(Type t)
            {
                if (t == typeof(String))
                {
                    return null;
                }
                //return FormatterServices.GetSafeUninitializedObject(t);

                // 如果类型没有无参数构造函数,则可能异常
                try
                {
                    return TypeX.CreateInstance(t);
                }
                catch { return FormatterServices.GetSafeUninitializedObject(t); }
            }));
        }
Esempio n. 20
0
        /// <summary>
        /// [OLD Code]返回一个新创建的实体对象,并给各个字段赋值
        /// </summary>
        /// <param name="typeName">完整实体名称, [命名空间.实体名称]</param>
        /// <param name="rval">表单集合字符串</param>
        /// <returns></returns>
        public static object GetFormEntity(this string rval, string typeName)
        {
            typeName = string.Format("{0}.{1}", ConfigHelper.GetAppSettings("EntitySpaceName"), typeName);
            TypeX  EntityType = TypeX.Create(TypeX.GetType(typeName, true));   //根据类的完整名称建立类的类型,用于动态创建类 如: Clump.Mobile.Models.NewsInfo
            Object objEntity  = EntityType.CreateInstance();                   //动态建立类的对象 实体类的对象Object objEntity = EntityType.CreateInstance(true);意思是在创建实体对象时 A a = new A(true)

            PropertyInfo[] props        = objEntity.GetType().GetProperties(); //获取此对象的,字段集合
            object         propertValue = String.Empty;

            foreach (PropertyInfo item in props)
            {
                propertValue = rval.GetFromValue(item.Name);
                if (!"".Equals(propertValue))
                {
                    //根据字段类型,转换格式
                    switch ((PropertyInfoX.Create(EntityType, item.Name)).Property.PropertyType.Name)
                    {
                    case "String": propertValue = Convert.ToString(propertValue); break;

                    case "Int64": propertValue = Convert.ToInt64(propertValue); break;

                    case "Int32": propertValue = Convert.ToInt32(propertValue); break;

                    case "Int16": propertValue = Convert.ToInt16(propertValue); break;

                    case "Byte": propertValue = Convert.ToByte(propertValue); break;

                    case "Single": propertValue = Convert.ToSingle(propertValue); break;

                    case "Double": propertValue = Convert.ToDouble(propertValue); break;

                    case "Boolean": propertValue = Convert.ToBoolean(propertValue); break;

                    case "DateTime": propertValue = Convert.ToDateTime(propertValue); break;

                    default: break;
                    }
                    PropertyInfoX.SetValue(objEntity, item.Name, propertValue);//给字段赋值
                }
            }
            PropertyInfoX.SetValue(objEntity, "CreateTime", DateTime.Now);//给CreateTime字段赋值,添加时间字段是每个数据表标配(未解决:MySql配置,暂时不能默认添加当前时间)
            return(objEntity);
        }
Esempio n. 21
0
        /// <summary>确保实体类已经执行完静态构造函数,因为那里实在是太容易导致死锁了</summary>
        /// <param name="type"></param>
        internal static void EnsureInit(Type type)
        {
            if (_hasInited.Contains(type))
            {
                return;
            }
            lock (_hasInited)
            // 如果这里锁定_hasInited,还是有可能死锁,因为可能实体类A的静态构造函数中可能导致调用另一个实体类的EnsureInit
            // 其实我们这里加锁的目的,本来就是为了避免重复添加同一个type而已
            //lock ("_hasInited" + type.FullName)
            {
                if (_hasInited.Contains(type))
                {
                    return;
                }

                TypeX.CreateInstance(type);
                _hasInited.Add(type);
            }
        }
Esempio n. 22
0
        /// <summary>加载数据表。无数据时返回空集合而不是null。</summary>
        /// <param name="dt">数据表</param>
        /// <returns>实体数组</returns>
        public IEntityList LoadData(DataTable dt)
        {
            //if (dt == null || dt.Rows.Count < 1) return null;

            // 准备好实体列表
            //EntityList<TEntity> list = new EntityList<TEntity>(dt.Rows.Count);
            IEntityList list = TypeX.CreateInstance(typeof(EntityList <>).MakeGenericType(EntityType), dt.Rows.Count) as IEntityList;

            if (dt == null || dt.Rows.Count < 1)
            {
                return(list);
            }

            List <FieldItem> ps   = new List <FieldItem>();
            List <String>    exts = new List <String>();

            foreach (DataColumn item in dt.Columns)
            {
                String    name = item.ColumnName;
                FieldItem fi   = null;
                if (FieldItems.TryGetValue(name, out fi))
                {
                    ps.Add(fi);
                }
                else
                {
                    exts.Add(name);
                }
            }

            // 遍历每一行数据,填充成为实体
            foreach (DataRow dr in dt.Rows)
            {
                //TEntity obj = new TEntity();
                // 由实体操作者创建实体对象,因为实体操作者可能更换
                IEntity obj = Factory.Create();
                LoadData(dr, obj, ps, exts);
                list.Add(obj);
            }
            return(list);
        }
Esempio n. 23
0
        /// <summary>初始化</summary>
        static void Init()
        {
            var container = ObjectContainer.Current;
            var asm       = Assembly.GetExecutingAssembly();

            // 搜索已加载程序集里面的消息类型
            foreach (var item in AssemblyX.FindAllPlugins(typeof(Message), true))
            {
                var msg = TypeX.CreateInstance(item) as Message;
                if (msg != null)
                {
                    if (item.Assembly != asm && msg.Kind < MessageKind.UserDefine)
                    {
                        throw new XException("不允许{0}采用小于{1}的保留编码{2}!", item.FullName, MessageKind.UserDefine, msg.Kind);
                    }

                    container.Register(typeof(Message), null, msg, msg.Kind);
                }
                //if (msg != null) container.Register<Message>(msg, msg.Kind);
            }
        }
Esempio n. 24
0
        IList ToArray(Type type)
        {
            //if (Count < 1) return null;

            // 元素类型
            if (type == null)
            {
                type = EntityType;
            }
            // 泛型
            type = typeof(EntityListView <>).MakeGenericType(type);

            // 初始化集合,实际上是创建了一个真正的实体类型
            IList list = TypeX.CreateInstance(type) as IList;

            for (int i = 0; i < Count; i++)
            {
                list.Add(this[i]);
            }

            return(list);
        }
Esempio n. 25
0
        /// <summary>
        ///     初始化
        /// </summary>
        private static void Init()
        {
            var container = ObjectContainer.Current;
            var asm       = Assembly.GetExecutingAssembly();

            // 搜索已加载程序集里面的消息类型
            foreach (var item in AssemblyX.FindAllPlugins(typeof(IRequest), true))
            {
                var msg = TypeX.CreateInstance(item) as IRequest;
                if (msg != null)
                {
                    container.Register(typeof(IRequest), item, null, msg.Function);
                }
            }

            foreach (var item in AssemblyX.FindAllPlugins(typeof(IResponse), true))
            {
                var msg = TypeX.CreateInstance(item) as IResponse;
                if (msg != null)
                {
                    container.Register(typeof(IResponse), item, null, msg.Function);
                }
            }
        }
Esempio n. 26
0
        public override bool Start()
        {
            base.Start();
            return(false);

            try
            {
                //CreateAllTransport();

                var types = AssemblyX.FindAllPlugins(typeof(IWork), true);
                //var types1=AssemblyX.FindAllPlugins("typeof()")
                _works = types.Select(t => (IWork)TypeX.CreateInstance(t));
                int count = 0;
                foreach (var work in _works)
                {
                    count++;
                }
                ServiceLogger.Current.WriteDebugLog("加载工作IWork插件{0}个:{1}", count, _works.Select(iw => iw.GetType().Name).Join(","));
            }
            catch (Exception ex)
            {
                ServiceLogger.Current.WriteError("加载工作插件IWork失败");
                ServiceLogger.Current.WriteException(ex);
                return(false);
            }

            if (_works != null && _works.Any())
            {
                _works.ForEach(iw =>
                {
                    iw.Start();
                    ServiceLogger.Current.WriteLog("{0}开始工作", iw.GetType().Name);
                });
            }
            return(true);
        }
Esempio n. 27
0
        private Object Resolve(Type from, Boolean getInstance, Object id, Boolean extend)
        {
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            // 名称不能是null,否则字典里面会报错
            if (id == null)
            {
                id = String.Empty;
            }

            var dic = Find(from, false);

            // 1,如果容器里面没有这个类型,则返回空
            // 这个type可能是接口类型
            if (dic == null)
            {
                return(null);
            }

            // 2,如果容器里面包含这个类型,并且指向的实例不为空,则返回
            // 根据名称去找,找不到返回空
            var map = FindMap(dic, id, extend);

            if (map == null)
            {
                return(null);
            }
            // 如果就是为了取实例,直接返回
            if (getInstance)
            {
                return(map.Instance);
            }
            // 否则每次都实例化
            //if (map.Instance != null) return map.Instance;

            // 检查是否指定实现类型,这种可能性极低,根本就不应该存在
            if (map.ImplementType == null)
            {
                throw new XException("设计错误,名为{0}的{1}实现未找到!", id, from);
            }

            Object obj = null;
            // 3,如果容器里面包含这个类型,并且指向的实例为空,则创建对象返回
            // 4,如果有带参数构造函数,则从容器内获取各个参数的实例,最后创建对象返回
            var cis = map.ImplementType.GetConstructors();

            if (cis.Length <= 0)
            {
                obj = TypeX.CreateInstance(map.ImplementType);
            }
            else
            {
                // 找到无参数构造函数
                var ci = map.ImplementType.GetConstructor(Type.EmptyTypes);
                if (ci != null)
                {
                    obj = ConstructorInfoX.Create(ci).CreateInstance(null);
                }
                else
                {
                    #region 构造函数注入
                    // 参数值缓存,避免相同类型参数,出现在不同构造函数中,造成重复Resolve的问题
                    var pscache = new Dictionary <Type, Object>();
                    foreach (var item in cis)
                    {
                        var ps = new List <Object>();
                        foreach (var pi in item.GetParameters())
                        {
                            Object pv = null;
                            // 处理值类型
                            if (pi.ParameterType.IsValueType)
                            {
                                pv = TypeX.CreateInstance(pi.ParameterType);
                                ps.Add(pv);
                                continue;
                            }

                            // 从缓存里面拿
                            if (pscache.TryGetValue(pi.ParameterType, out pv))
                            {
                                ps.Add(pv);
                                continue;
                            }

                            dic = Find(pi.ParameterType, false);
                            if (dic != null && dic.Count > 0)
                            {
                                // 解析该参数类型的实例
                                pv = Resolve(pi.ParameterType);
                                if (pv != null)
                                {
                                    pscache.Add(pi.ParameterType, pv);
                                    ps.Add(pv);
                                    continue;
                                }
                            }

                            // 任意一个参数解析失败,都将导致失败
                            ps = null;
                            break;
                        }
                        // 取得完整参数,可以构造了
                        if (ps != null)
                        {
                            obj = ConstructorInfoX.Create(item).CreateInstance(ps.ToArray());
                            break;
                        }
                    }

                    // 遍历完所有构造函数都无法构造,失败!
                    if (obj == null)
                    {
                        throw new XException("容器无法完整构造目标对象的任意一个构造函数!");
                    }
                    #endregion
                }
            }

            //// 赋值注入
            //foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(obj))
            //{
            //    if (!pd.IsReadOnly && Stores.ContainsKey(pd.PropertyType)) pd.SetValue(obj, Resolve(pd.PropertyType));
            //}

            return(obj);
        }
Esempio n. 28
0
        /// <summary>遍历所有程序集的所有类型,自动注册实现了指定接口或基类的类型。如果没有注册任何实现,则默认注册第一个排除类型</summary>
        /// <param name="from">接口或基类</param>
        /// <param name="getidCallback">用于从外部类型对象中获取标识的委托</param>
        /// <param name="id">标识</param>
        /// <param name="priority">优先级</param>
        /// <param name="excludeTypes">要排除的类型,一般是内部默认实现</param>
        /// <returns></returns>
        public virtual IObjectContainer AutoRegister(Type from, Func <Object, Object> getidCallback = null, Object id = null, Int32 priority = 0, params Type[] excludeTypes)
        {
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }

            if (excludeTypes == null)
            {
                excludeTypes = Type.EmptyTypes;
            }

            // 如果存在已注册项,并且优先级大于0,那么这里就不要注册了
            var dic = Find(from, false);

            if (dic != null)
            {
                var map = FindMap(dic, null, false) as Map;
                if (map != null && map.Priority > 0)
                {
                    return(this);
                }
            }

            IEnumerable <Type> listType = AssemblyX.FindAllPlugins(from, true);

            // 遍历所有程序集,自动加载
            foreach (var item in AssemblyX.FindAllPlugins(from, true))
            {
                if (Array.IndexOf(excludeTypes, item) < 0)
                {
                    // 自动注册的优先级是1,高于默认的0
                    //Register(from, item, null, null, 1);
                    // 实例化一次,让这个类有机会执行类型构造函数,可以获取旧的类型实现
                    var obj = TypeX.CreateInstance(item);
                    // 如果指定了获取ID的委托,并且取得的ID与传入ID不一致,则不承认
                    if (getidCallback != null && id != getidCallback(obj))
                    {
                        continue;
                    }

                    if (XTrace.Debug)
                    {
                        XTrace.WriteLine("为{0}自动注册{1},标识={2},优先级={3}!", from.FullName, item.FullName, id, priority + 1);
                    }

                    Register(from, null, obj, id, priority + 1);
                    return(this);
                }
            }

            // 如果没有注册任何实现,则默认注册第一个排除类型
            if (excludeTypes.Length > 0)
            {
                //if (dic == null)
                {
                    Register(from, excludeTypes[0], null, id, priority);
                }
            }

            return(this);
        }
Esempio n. 29
0
        /// <summary>
        /// 预先修正表名等各种东西,简化模版编写。
        /// 因为与设置相关,所以,每次更改设置后,都应该调用一次该方法。
        /// </summary>
        List <IDataTable> FixTable(List <IDataTable> tables)
        {
            if (tables == null || tables.Count < 1)
            {
                return(tables);
            }

            var type = tables[0].GetType();
            var list = tables.Select(dt => (TypeX.CreateInstance(type) as IDataTable).CopyAllFrom(dt)).ToList();

            var noCNDic    = new Dictionary <object, string>();
            var existTrans = new List <string>();

            var mr = ObjectContainer.Current.Resolve <IModelResolver>();

            mr.AutoCutPrefix    = Config.AutoCutPrefix;
            mr.AutoCutTableName = Config.AutoCutTableName;
            mr.AutoFixWord      = Config.AutoFixWord;
            mr.FilterPrefixs    = Config.Prefix.Split(',', ';');
            mr.UseID            = Config.UseID;

            #region 修正数据
            foreach (var table in list)
            {
                table.Alias = mr.GetAlias(table.Name);

                if (String.IsNullOrEmpty(table.Description))
                {
                    noCNDic.Add(table, table.Alias);
                }
                else
                {
                    AddExistTranslate(existTrans, !string.IsNullOrEmpty(table.Alias) ? table.Alias : table.Name, table.Description);
                }

                // 字段
                foreach (var dc in table.Columns)
                {
                    dc.Alias = mr.GetAlias(dc);

                    if (String.IsNullOrEmpty(dc.Description))
                    {
                        noCNDic.Add(dc, dc.Alias);
                    }
                    else
                    {
                        AddExistTranslate(existTrans, !string.IsNullOrEmpty(dc.Alias) ? dc.Alias : dc.Name, dc.Description);
                    }
                }

                //table.Fix();
            }

            ModelHelper.Connect(list);
            #endregion

            #region 异步调用接口修正中文名
            //if (Config.UseCNFileName && noCNDic.Count > 0)
            if (noCNDic.Count > 0)
            {
                ThreadPoolX.QueueUserWorkItem(TranslateWords, noCNDic);
            }
            #endregion

            #region 提交已翻译的项目
            if (existTrans.Count > 0)
            {
                ThreadPoolX.QueueUserWorkItem(SubmitTranslateNew, existTrans.ToArray());
            }
            #endregion

            return(list);
        }
Esempio n. 30
0
        private static IEnumerable <IDataSync> InitPlugins()
        {
            var ps = AssemblyX.FindAllPlugins(typeof(IDataSync), true);

            return(ps.Select(e => (IDataSync)TypeX.CreateInstance(e)));
        }