文章目錄 生命周期 PreConfigureServices 添加依賴註入或者其它配置之前 ConfigureServices 添加依賴註入或者其它配置 PostConfigureServices 添加依賴註入或者其它配置之後 OnPreApplicationInitialization 初始化所有 ...
生命周期
- PreConfigureServices 添加依賴註入或者其它配置之前
- ConfigureServices 添加依賴註入或者其它配置
- PostConfigureServices 添加依賴註入或者其它配置之後
- OnPreApplicationInitialization 初始化所有模塊之前
- OnApplicationInitialization 初始化所有模塊
- OnPostApplicationInitialization 初始化所有模塊之後
- OnApplicationShutdown 應用關閉執行
OnPreApplicationInitialization和OnPostApplicationInitialization方法用來在OnApplicationInitialization之前或之後覆蓋和編寫你的代碼.請註意,在這些方法中編寫的代碼將在所有其他模塊的OnApplicationInitialization方法之前/之後執行.
載入流程
- 進入到Startup
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddApplication<xxxManagementHttpApiHostModule>();
}
}
- 查看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;
}
- 進入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);
}
- 查看AbpApplicationBase構造函數
internal AbpApplicationBase(
[NotNull] Type startupModuleType,
[NotNull] IServiceCollection services,
Action<AbpApplicationCreationOptions>? optionsAction)
{
services.AddCoreServices();
services.AddCoreAbpServices(this, options);
// 載入模塊
Modules = LoadModules(services, options);
}
- 查看載入模塊邏輯
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>();
});
}
註冊了這四個生命周期,在什麼時候調用呢?請繼續往下看。
- 繼續回到Startup類
public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.InitializeApplication();
}
}
- 查看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
- Abp Vnext Pro Github地址 的 Vue3 實現版本 開箱即用的中後臺前端/設計解決方案.
- 文檔地址
- 演示地址:用戶名admin 密碼1q2w3E*
- Abp Vnext Pro Suite Github地址 代碼生成器。
- 演示地址:用戶名admin 密碼1q2w3E*
- 視頻教程