Example #1
0
        private void AddContainer(Type type, ContainerAttribute attrContainer, bool isNew = false)
        {
            var logger = new UnitLogger("IocManager");

            if (type.GetInterfaces().Where(p => p.FullName == attrContainer.BaseType.FullName).Count() == 0 && type.BaseType != attrContainer.BaseType)
            {
                logger.Error($"类型{type.FullName}没有继承自{attrContainer.BaseType.FullName},无法注册到容器");
            }
            else
            {
                var key = new ContainerKey(attrContainer.ModuleName, attrContainer.BaseType.FullName);
                if (ContainerDic.Keys.Contains(key))
                {
                    if (isNew)
                    {
                        ContainerDic.Remove(key);
                    }
                    else
                    {
                        logger.Warn($"类型:{type.FullName},模块:{attrContainer.ModuleName},继承自{attrContainer.BaseType.FullName},已经注册到容器,无法再次注册");
                    }
                }
                var args = new ContainerArgs(type, attrContainer);
                logger.Info($"类型:{type.FullName},模块:{attrContainer.ModuleName},继承自{attrContainer.BaseType.FullName},成功注册到容器");
                ContainerDic.Add(key, args);
            }
        }
Example #2
0
        public T TryResolve <T>(string moduleName = "")
        {
            var parent = typeof(T).FullName;
            var key    = new ContainerKey(moduleName, parent);

            //ContainerArgs.FirstOrDefault(p => p.ParentType.Count(d => d.FullName == parent.FullName) > 0 && p.ContainerAttribute.ModuleName == moduleName);
            if (!ContainerDic.Keys.Contains(key))
            {
                return(default(T));
            }
            return((T)ContainerDic[key].GetInstance());
        }
Example #3
0
        public T Resolve <T>(string moduleName = "")
        {
            var parent = typeof(T).FullName;
            var key    = new ContainerKey(moduleName, parent);

            //ContainerArgs.FirstOrDefault(p => p.ParentType.Count(d => d.FullName == parent.FullName) > 0 && p.ContainerAttribute.ModuleName == moduleName);
            if (!ContainerDic.Keys.Contains(key))
            {
                string msg = $"容器内没有找到基类型为{parent},模块为{moduleName}的注册信息";
                Logger.GetLogger("IocManager").Fatal(msg);
                throw new KeyNotFoundException(msg);
            }
            return((T)ContainerDic[key].GetInstance());
        }