using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using DS.Module.Core.Extensions; using DS.Module.Core.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace DS.Module.Core.Modules; public class ModuleApplicationBase : IModuleApplication { public Type StartupModuleType { get; set; } public IServiceCollection Services { get; set; } public IServiceProvider ServiceProvider { get; set; } /// /// 模块接口容器 /// public IReadOnlyList Modules { get; set; } public List Source { get; protected set; } public ModuleApplicationBase(Type startupModuleType, IServiceCollection services) { StartupModuleType = startupModuleType; Services = services; services.TryAddSingleton(); services.TryAddSingleton(); services.AddSingleton(this); services.TryAddObjectAccessor(); Source = this.GetAllModule(services); Modules = this.LoadModules(); } protected virtual List GetAllModule(IServiceCollection services) { var typeFinder = services.GetOrAddSingletonService(); var typs = typeFinder.Find(o => DSAppModule.IsAppModule(o)); var modules = typs.Select(o => CreateModule(services, o)).Distinct(); return modules.ToList(); } protected virtual void SetServiceProvider(IServiceProvider serviceProvider) { ServiceProvider = serviceProvider; ServiceProvider.GetRequiredService>().Value = ServiceProvider; } /// /// 获取所有需要加载的模块 /// /// protected virtual IReadOnlyList LoadModules() { List modules = new List(); var module = Source.FirstOrDefault(o => o.GetType() == StartupModuleType); //if (module == null) //{ // throw new Exception($"类型为“{StartupModuleType.FullName}”的模块实例无法找到"); //} Console.WriteLine("当前启动模块:",module); modules.Add(module); var dependeds = module.GetDependedTypes(); foreach (var dependType in dependeds.Where(o => DSAppModule.IsAppModule(o))) { var dependModule = Source.ToList().Find(m => m.GetType() == dependType); if (dependModule == null) { throw new Exception($"加载模块{module.GetType().FullName}时无法找到依赖模块{dependType.FullName}"); } modules.AddIfNotContains(dependModule); } return modules; } /// /// 创建模块 /// /// /// /// private IDSAppModule CreateModule(IServiceCollection services, Type moduleType) { var module = (IDSAppModule)Expression.Lambda(Expression.New(moduleType)).Compile().DynamicInvoke(); services.AddSingleton(moduleType, module); return module; } public virtual void Dispose() { } }