Abp vNext 模組載入機制

WangJunZzz發表於2023-09-25

文章目錄

生命週期

  • PreConfigureServices 新增依賴注入或者其它配置之前
  • ConfigureServices 新增依賴注入或者其它配置
  • PostConfigureServices 新增依賴注入或者其它配置之後
  • OnPreApplicationInitialization 初始化所有模組之前
  • OnApplicationInitialization 初始化所有模組
  • OnPostApplicationInitialization 初始化所有模組之後
  • OnApplicationShutdown 應用關閉執行

OnPreApplicationInitializationOnPostApplicationInitialization方法用來在OnApplicationInitialization之前或之後覆蓋和編寫你的程式碼.請注意,在這些方法中編寫的程式碼將在所有其他模組的OnApplicationInitialization方法之前/之後執行.

載入流程

  1. 進入到Startup
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplication<xxxManagementHttpApiHostModule>();
    }
}
  1. 檢視AddApplication原始碼會呼叫AbpApplicationFactory.CreateAsync
public async static Task<IAbpApplicationWithExternalServiceProvider> CreateAsync(
    [NotNull] Type startupModuleType,
    [NotNull] IServiceCollection services,
    Action<AbpApplicationCreationOptions>? optionsAction = null)
{
    var app = new AbpApplicationWithExternalServiceProvider(startupModuleType, services, options =>
    {
        options.SkipConfigureServices = true;
        optionsAction?.Invoke(options);
    });
    await app.ConfigureServicesAsync();
    return app;
}
  1. 進入AbpApplicationWithExternalServiceProvider,我們可以看到繼承AbpApplicationBase
internal class AbpApplicationWithExternalServiceProvider : AbpApplicationBase, IAbpApplicationWithExternalServiceProvider
{
    public AbpApplicationWithExternalServiceProvider(
        [NotNull] Type startupModuleType,
        [NotNull] IServiceCollection services,
        Action<AbpApplicationCreationOptions>? optionsAction
        ) : base(
            startupModuleType,
            services,
            optionsAction)
    {
        services.AddSingleton<IAbpApplicationWithExternalServiceProvider>(this);
    }

    void IAbpApplicationWithExternalServiceProvider.SetServiceProvider([NotNull] IServiceProvider serviceProvider)
    {
        Check.NotNull(serviceProvider, nameof(serviceProvider));

        // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
        if (ServiceProvider != null)
        {
            if (ServiceProvider != serviceProvider)
            {
                throw new AbpException("Service provider was already set before to another service provider instance.");
            }

            return;
        }

        SetServiceProvider(serviceProvider);
    }
  1. 檢視AbpApplicationBase建構函式
 internal AbpApplicationBase(
        [NotNull] Type startupModuleType,
        [NotNull] IServiceCollection services,
        Action<AbpApplicationCreationOptions>? optionsAction)
    {
        services.AddCoreServices();
        services.AddCoreAbpServices(this, options);
        // 載入模組
        Modules = LoadModules(services, options);
    }
  1. 檢視載入模組邏輯
public IAbpModuleDescriptor[] LoadModules(
    IServiceCollection services,
    Type startupModuleType,
    PlugInSourceList plugInSources)
{
    Check.NotNull(services, nameof(services));
    Check.NotNull(startupModuleType, nameof(startupModuleType));
    Check.NotNull(plugInSources, nameof(plugInSources));
    // 掃描模組
    var modules = GetDescriptors(services, startupModuleType, plugInSources);
    // 按照模組的依賴性重新排序
    modules = SortByDependency(modules, startupModuleType);
    return modules.ToArray();
}

生命週期

在上面第二步我們可以看到有一個await app.ConfigureServicesAsync();

  • 在這個方法中可以看到依次執行每個模組的PreConfigureServices,ConfigureServices,PostConfigureServices
public virtual async Task ConfigureServicesAsync()
    {
        CheckMultipleConfigureServices();

        var context = new ServiceConfigurationContext(Services);
        Services.AddSingleton(context);

        foreach (var module in Modules)
        {
            if (module.Instance is AbpModule abpModule)
            {
                abpModule.ServiceConfigurationContext = context;
            }
        }

        //PreConfigureServices
        foreach (var module in Modules.Where(m => m.Instance is IPreConfigureServices))
        {
            try
            {
                await ((IPreConfigureServices)module.Instance).PreConfigureServicesAsync(context);
            }
            catch (Exception ex)
            {
                throw new AbpInitializationException($"An error occurred during {nameof(IPreConfigureServices.PreConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex);
            }
        }

        var assemblies = new HashSet<Assembly>();

        //ConfigureServices
        foreach (var module in Modules)
        {
            if (module.Instance is AbpModule abpModule)
            {
                if (!abpModule.SkipAutoServiceRegistration)
                {
                    var assembly = module.Type.Assembly;
                    if (!assemblies.Contains(assembly))
                    {
                        Services.AddAssembly(assembly);
                        assemblies.Add(assembly);
                    }
                }
            }

            try
            {
                await module.Instance.ConfigureServicesAsync(context);
            }
            catch (Exception ex)
            {
                throw new AbpInitializationException($"An error occurred during {nameof(IAbpModule.ConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex);
            }
        }

        //PostConfigureServices
        foreach (var module in Modules.Where(m => m.Instance is IPostConfigureServices))
        {
            try
            {
                await ((IPostConfigureServices)module.Instance).PostConfigureServicesAsync(context);
            }
            catch (Exception ex)
            {
                throw new AbpInitializationException($"An error occurred during {nameof(IPostConfigureServices.PostConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex);
            }
        }

        foreach (var module in Modules)
        {
            if (module.Instance is AbpModule abpModule)
            {
                abpModule.ServiceConfigurationContext = null!;
            }
        }

        _configuredServices = true;
    }
  • 再次檢視第四步中有一個services.AddCoreAbpServices(this, options);
    這個裡面構造好其它的四個生命週期
internal static void AddCoreAbpServices(this IServiceCollection services,
    IAbpApplication abpApplication,
    AbpApplicationCreationOptions applicationCreationOptions)
{
    var moduleLoader = new ModuleLoader();
    var assemblyFinder = new AssemblyFinder(abpApplication);
    var typeFinder = new TypeFinder(assemblyFinder);
    if (!services.IsAdded<IConfiguration>())
    {
        services.ReplaceConfiguration(
            ConfigurationHelper.BuildConfiguration(
                applicationCreationOptions.Configuration
            )
        );
    }
    services.TryAddSingleton<IModuleLoader>(moduleLoader);
    services.TryAddSingleton<IAssemblyFinder>(assemblyFinder);
    services.TryAddSingleton<ITypeFinder>(typeFinder);
    services.TryAddSingleton<IInitLoggerFactory>(new DefaultInitLoggerFactory());
    services.AddAssemblyOf<IAbpApplication>();
    services.AddTransient(typeof(ISimpleStateCheckerManager<>), typeof(SimpleStateCheckerManager<>));
    // 註冊生命週期
    services.Configure<AbpModuleLifecycleOptions>(options =>
    {
        // OnPreApplicationInitialization
        options.Contributors.Add<OnPreApplicationInitializationModuleLifecycleContributor>();
        // OnApplicationInitialization
        options.Contributors.Add<OnApplicationInitializationModuleLifecycleContributor>();
        // OnPostApplicationInitialization
        options.Contributors.Add<OnPostApplicationInitializationModuleLifecycleContributor>();
        // OnApplicationShutdown
        options.Contributors.Add<OnApplicationShutdownModuleLifecycleContributor>();
    });
}

註冊了這四個生命週期,在什麼時候呼叫呢?請繼續往下看。

  1. 繼續回到Startup類
public class Startup
{
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.InitializeApplication();
    }
}
  1. 檢視InitializeApplication
  • 遍歷剛剛注入的四個生命週期,執行Initialize初始化方法
public void InitializeModules(ApplicationInitializationContext context)
{
    foreach (var contributor in _lifecycleContributors)
    {
        foreach (var module in _moduleContainer.Modules)
        {
            try
            {
                contributor.Initialize(context, module.Instance);
            }
            catch (Exception ex)
            {
                //
            }
        }
    }
    _logger.LogInformation("Initialized all ABP modules.");
}

Abp vNext Pro

如果覺得可以,不要吝嗇你的小星星哦

文章目錄

相關文章