Beispiel #1
0
        public IDatabaseApi GetOrAddDatabaseApi(string key, Func <IDatabaseApi> factory)
        {
            XqCheck.NotNull(key, nameof(key));
            XqCheck.NotNull(factory, nameof(factory));

            return(_databaseApis.GetOrAdd(key, factory));
        }
        /// <summary>
        /// 创建一个启动模块类型为<paramref name="startupModuleType"/>的应用,
        /// ,相关的IServiceCollection为<paramref name="services"/>,同时执行<paramref name="optionsAction"/>
        /// </summary>
        /// <param name="startupModuleType">启动模块</param>
        /// <param name="services">该应用所需的服务</param>
        /// <param name="optionsAction"></param>
        internal XqApplicationBase(
            [NotNull] Type startupModuleType,
            [NotNull] IServiceCollection services,
            [CanBeNull] Action <XqApplicationCreationOptions> optionsAction)
        {
            XqCheck.NotNull(startupModuleType, nameof(startupModuleType));
            XqCheck.NotNull(services, nameof(services));

            StartupModuleType = startupModuleType;
            Services          = services;

            services.TryAddObjectAccessor <IServiceProvider>();

            var options = new XqApplicationCreationOptions(services);

            optionsAction?.Invoke(options);

            ///增加<see cref="IXqApplication"/>应用服务
            services.AddSingleton <IXqApplication>(this);

            ///增加<see cref="IModuleContainer"/>服务
            services.AddSingleton <IModuleContainer>(this);

            ///添加应用的核心服务
            services.AddCoreServices();

            services.AddCoreXqServices(this, options);

            Modules = LoadModules(services, options);
        }
Beispiel #3
0
        public void Configure <TDbContext>([NotNull] Action <XqDbContextConfigurationContext <TDbContext> > action)
            where TDbContext : XqDbContext <TDbContext>
        {
            XqCheck.NotNull(action, nameof(action));

            ConfigureActions[typeof(TDbContext)] = action;
        }
Beispiel #4
0
        public virtual void Reserve(string reservationName)
        {
            XqCheck.NotNull(reservationName, nameof(reservationName));

            ReservationName = reservationName;
            IsReserved      = true;
        }
Beispiel #5
0
        /// <summary>
        /// 创建一个短信信息
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="text"></param>
        public SmsMessage([NotNull] string phoneNumber, [NotNull] string text)
        {
            PhoneNumber = XqCheck.NotNullOrWhiteSpace(phoneNumber, nameof(phoneNumber));
            Text        = XqCheck.NotNullOrWhiteSpace(text, nameof(text));

            Properties = new Dictionary <string, object>();
        }
Beispiel #6
0
        public ITransactionApi GetOrAddTransactionApi(string key, Func <ITransactionApi> factory)
        {
            XqCheck.NotNull(key, nameof(key));
            XqCheck.NotNull(factory, nameof(factory));

            return(_transactionApis.GetOrAdd(key, factory));
        }
Beispiel #7
0
        /// <summary>
        /// 通过Factory构建ServiceProvider
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceProvider BuildServiceProviderFromFactory([NotNull] this IServiceCollection services)
        {
            XqCheck.NotNull(services, nameof(services));

            foreach (var service in services)
            {
                var factoryInterface = service.ImplementationInstance?.GetType()
                                       .GetTypeInfo()
                                       .GetInterfaces()
                                       .FirstOrDefault(i => i.GetTypeInfo().IsGenericType&&
                                                       i.GetGenericTypeDefinition() == typeof(IServiceProviderFactory <>));

                if (factoryInterface == null)
                {
                    continue;
                }

                var containerBuilderType = factoryInterface.GenericTypeArguments[0];
                return((IServiceProvider)typeof(ServiceCollectionCommonExtensions)
                       .GetTypeInfo()
                       .GetMethods()
                       .Single(m => m.Name == nameof(BuildServiceProviderFromFactory) && m.IsGenericMethod)
                       .MakeGenericMethod(containerBuilderType)
                       .Invoke(null, new object[] { services, null }));
            }

            return(services.BuildServiceProvider());
        }
        /// <summary>
        /// <see cref="XqApplicationWithExternalServiceProvider"/>的初始化,设置应用的<see cref="IServiceProvider"/>,进行Module的初始化
        /// </summary>
        /// <param name="serviceProvider"></param>
        public void Initialize(IServiceProvider serviceProvider)
        {
            XqCheck.NotNull(serviceProvider, nameof(serviceProvider));

            SetServiceProvider(serviceProvider);

            InitializeModules();
        }
        public FolderPlugInSource(
            [NotNull] string folder,
            SearchOption searchOption = SearchOption.TopDirectoryOnly)
        {
            XqCheck.NotNull(folder, nameof(folder));

            Folder       = folder;
            SearchOption = searchOption;
        }
Beispiel #10
0
        /// <summary>
        /// 读取文件内容,并且按照<see cref="Byte"/>返回
        /// </summary>
        public static byte[] ReadBytes([NotNull] this IFileInfo fileInfo)
        {
            XqCheck.NotNull(fileInfo, nameof(fileInfo));

            using (var stream = fileInfo.CreateReadStream())
            {
                return(stream.GetAllBytes());
            }
        }
Beispiel #11
0
        public ChildUnitOfWork([NotNull] IUnitOfWork parent)
        {
            XqCheck.NotNull(parent, nameof(parent));

            _parent = parent;

            _parent.Failed   += (sender, args) => { Failed.InvokeSafely(sender, args); };
            _parent.Disposed += (sender, args) => { Disposed.InvokeSafely(sender, args); };
        }
Beispiel #12
0
        /// <summary>
        /// 读取文件内容,并且按照<see cref="Byte"/>返回
        /// </summary>
        public static async Task <byte[]> ReadBytesAsync([NotNull] this IFileInfo fileInfo)
        {
            XqCheck.NotNull(fileInfo, nameof(fileInfo));

            using (var stream = fileInfo.CreateReadStream())
            {
                return(await stream.GetAllBytesAsync().ConfigureAwait(false));
            }
        }
Beispiel #13
0
        public static Type[] GetModulesWithAllDependencies([NotNull] this IPlugInSource plugInSource)
        {
            XqCheck.NotNull(plugInSource, nameof(plugInSource));

            return(plugInSource
                   .GetModules()
                   .SelectMany(XqModuleHelper.FindAllModuleTypes)
                   .Distinct()
                   .ToArray());
        }
Beispiel #14
0
        /// <summary>
        /// 创建一个<see cref="EmbeddedFileSet"/>对象
        /// </summary>
        /// <param name="assembly">程序集</param>
        /// <param name="baseNamespace">命名空间</param>
        /// <param name="baseFolderInProject">文件夹</param>
        public EmbeddedFileSet(
            [NotNull] Assembly assembly,
            [CanBeNull] string baseNamespace       = null,
            [CanBeNull] string baseFolderInProject = null)
        {
            XqCheck.NotNull(assembly, nameof(assembly));

            Assembly            = assembly;
            BaseNamespace       = baseNamespace;
            BaseFolderInProject = baseFolderInProject;
        }
Beispiel #15
0
        /// <summary>
        /// 如果某个字符不在字符串开始,在字符串开始追加该字符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="c">被追加的字符</param>
        /// <param name="comparisonType">比较类型</param>
        /// <returns>处理完成的字符串</returns>
        public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType = StringComparison.Ordinal)
        {
            XqCheck.NotNull(str, nameof(str));

            if (str.StartsWith(c.ToString(), comparisonType))
            {
                return(str);
            }

            return(c + str);
        }
Beispiel #16
0
        /// <summary>
        /// 从结尾开始截取长度为<paramref name="len"/>的字符串
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
        /// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
        public static string Right(this string str, int len)
        {
            XqCheck.NotNull(str, nameof(str));

            if (str.Length < len)
            {
                throw new ArgumentException("len argument can not be bigger than given string's length!");
            }

            return(str.Substring(str.Length - len, len));
        }
Beispiel #17
0
        public void AddDatabaseApi(string key, IDatabaseApi api)
        {
            XqCheck.NotNull(key, nameof(key));
            XqCheck.NotNull(api, nameof(api));

            if (_databaseApis.ContainsKey(key))
            {
                throw new XqException("There is already a database API in this unit of work with given key: " + key);
            }

            _databaseApis.Add(key, api);
        }
Beispiel #18
0
        /// <summary>
        /// 使用给定的<paramref name="encoding"/>.读取文件内容  ,并且按照<see cref="String"/>返回
        /// </summary>
        public static string ReadAsString([NotNull] this IFileInfo fileInfo, Encoding encoding)
        {
            XqCheck.NotNull(fileInfo, nameof(fileInfo));

            using (var stream = fileInfo.CreateReadStream())
            {
                using (var streamReader = new StreamReader(stream, encoding, true))
                {
                    return(streamReader.ReadToEnd());
                }
            }
        }
Beispiel #19
0
        /// <summary>
        /// 通过<paramref name="options"/>进行<see cref="IUnitOfWork"/>初始化
        /// </summary>
        /// <param name="options"></param>
        public virtual void Initialize(XqUnitOfWorkOptions options)
        {
            XqCheck.NotNull(options, nameof(options));

            if (Options != null)
            {
                throw new XqException("This unit of work is already initialized before!");
            }

            Options    = _defaultOptions.Normalize(options.Clone());
            IsReserved = false;
        }
        /// <summary>
        /// 执行参数为<see cref="XqEntityOption{TEntity}"/>的<paramref name="optionsAction"/>
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="optionsAction"></param>
        public void Entity <TEntity>([NotNull] Action <XqEntityOption <TEntity> > optionsAction)
            where TEntity : IEntity
        {
            XqCheck.NotNull(optionsAction, nameof(optionsAction));

            optionsAction(
                _options.GetOrAdd(
                    typeof(TEntity),
                    () => new XqEntityOption <TEntity>()
                    ) as XqEntityOption <TEntity>
                );
        }
        /// <summary>
        /// 如果在<<paramref name="source"/>不存在,则增加<paramref name="item"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public static bool AddIfNotContains <T>([NotNull] this ICollection <T> source, T item)
        {
            XqCheck.NotNull(source, nameof(source));

            if (source.Contains(item))
            {
                return(false);
            }

            source.Add(item);
            return(true);
        }
Beispiel #22
0
        public IXqCommonDbContextRegistrationOptionsBuilder SetDefaultRepositoryClassesOption(
            Type repositoryImplementationType,
            Type repositoryImplementationTypeWithoutKey
            )
        {
            XqCheck.NotNull(repositoryImplementationType, nameof(repositoryImplementationType));
            XqCheck.NotNull(repositoryImplementationTypeWithoutKey, nameof(repositoryImplementationTypeWithoutKey));

            DefaultRepositoryImplementationType           = repositoryImplementationType;
            DefaultRepositoryImplementationTypeWithoutKey = repositoryImplementationTypeWithoutKey;

            return(this);
        }
Beispiel #23
0
        /// <summary>
        /// 根据<paramref name="startupModuleType"/>,遍历所有依赖模块,并进行加载
        /// </summary>
        /// <param name="services">系统服务</param>
        /// <param name="startupModuleType"></param>
        /// <param name="plugInSources"></param>
        /// <returns></returns>
        public IXqModuleDescriptor[] LoadModules(IServiceCollection services, Type startupModuleType, PlugInSourceList plugInSources)
        {
            XqCheck.NotNull(services, nameof(services));
            XqCheck.NotNull(startupModuleType, nameof(startupModuleType));
            XqCheck.NotNull(plugInSources, nameof(plugInSources));

            var moduledescs = GetDescriptors(services, startupModuleType, plugInSources);

            moduledescs = SortByDependency(moduledescs, startupModuleType);
            ConfigureServices(moduledescs, services);

            return(moduledescs.ToArray());
        }
        public static T GetOrAdd <T>([NotNull] this IList <T> source, Func <T, bool> selector, Func <T> factory)
        {
            XqCheck.NotNull(source, nameof(source));

            var item = source.FirstOrDefault(selector);

            if (item == null)
            {
                item = factory();
                source.Add(item);
            }

            return(item);
        }
Beispiel #25
0
        /// <summary>
        /// 注册类型为<typeparamref name="TDbContext"/>的预配置
        /// </summary>
        /// <typeparam name="TDbContext"></typeparam>
        /// <param name="action"></param>
        public void PreConfigure <TDbContext>([NotNull] Action <XqDbContextConfigurationContext <TDbContext> > action)
            where TDbContext : XqDbContext <TDbContext>
        {
            XqCheck.NotNull(action, nameof(action));

            var actions = PreConfigureActions.GetOrDefault(typeof(TDbContext));

            if (actions == null)
            {
                PreConfigureActions[typeof(TDbContext)] = actions = new List <object>();
            }

            actions.Add(action);
        }
Beispiel #26
0
        /// <summary>
        /// 获取虚拟文件或者物理文件的路径
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <returns></returns>
        public static string GetVirtualOrPhysicalPathOrNull([NotNull] this IFileInfo fileInfo)
        {
            XqCheck.NotNull(fileInfo, nameof(fileInfo));

            if (fileInfo is EmbeddedResourceFileInfo embeddedFileInfo)
            {
                return(embeddedFileInfo.VirtualPath);
            }

            if (fileInfo is InMemoryFileInfo inMemoryFileInfo)
            {
                return(inMemoryFileInfo.DynamicPath);
            }

            return(fileInfo.PhysicalPath);
        }
        /// <summary>
        /// 获得一个工作单元,如果<paramref name="requiresNew"/>为False,将把当前的Uow作为一个<see cref="ChildUnitOfWork"/>返回
        /// 如果<paramref name="requiresNew"/>为True,创建一个Uow
        /// </summary>
        /// <param name="options"></param>
        /// <param name="requiresNew"></param>
        /// <returns></returns>
        public IUnitOfWork Begin(XqUnitOfWorkOptions options, bool requiresNew = false)
        {
            XqCheck.NotNull(options, nameof(options));

            var currentUow = Current;

            if (currentUow != null && !requiresNew)
            {
                return(new ChildUnitOfWork(currentUow));
            }

            var unitOfWork = CreateNewUnitOfWork();

            unitOfWork.Initialize(options);

            return(unitOfWork);
        }
        /// <summary>
        /// 保留<see cref="IUnitOfWork"/>
        /// </summary>
        /// <param name="reservationName"></param>
        /// <param name="requiresNew"></param>
        /// <returns></returns>
        public IUnitOfWork Reserve(string reservationName, bool requiresNew = false)
        {
            XqCheck.NotNull(reservationName, nameof(reservationName));

            if (!requiresNew &&
                _ambientUnitOfWork.UnitOfWork != null &&
                _ambientUnitOfWork.UnitOfWork.IsReservedFor(reservationName))
            {
                return(new ChildUnitOfWork(_ambientUnitOfWork.UnitOfWork));
            }

            var unitOfWork = CreateNewUnitOfWork();

            unitOfWork.Reserve(reservationName);

            return(unitOfWork);
        }
        /// <summary>
        ///根据<paramref name="type"/>,<paramref name="instance"/>, 创建一个<see cref="XqModuleDescriptor"/>对象
        /// </summary>
        /// <param name="type">模块的类型</param>
        /// <param name="instance">模块的实例</param>
        /// <param name="isLoadedAsPlugIn">是否为外部加载</param>
        public XqModuleDescriptor(
            [NotNull] Type type,
            [NotNull] IXqModule instance,
            bool isLoadedAsPlugIn)
        {
            XqCheck.NotNull(type, nameof(type));
            XqCheck.NotNull(instance, nameof(instance));

            ///type与instance的type不一样
            if (!type.GetTypeInfo().IsAssignableFrom(instance.GetType()))
            {
                throw new ArgumentException($"Given module instance ({instance.GetType().AssemblyQualifiedName}) is not an instance of given module type: {type.AssemblyQualifiedName}");
            }

            Type             = type;
            Assembly         = type.Assembly;
            Instance         = instance;
            IsLoadedAsPlugIn = isLoadedAsPlugIn;

            _dependencies = new List <IXqModuleDescriptor>();
        }
        public bool TryBeginReserved(string reservationName, XqUnitOfWorkOptions options)
        {
            XqCheck.NotNull(reservationName, nameof(reservationName));

            var uow = _ambientUnitOfWork.UnitOfWork;

            //Find reserved unit of work starting from current and going to outers
            while (uow != null && !uow.IsReservedFor(reservationName))
            {
                uow = uow.Outer;
            }

            if (uow == null)
            {
                return(false);
            }

            uow.Initialize(options);

            return(true);
        }