簡介
在ABP中, 模板的定義就是一個類, 只需要繼承 AbpModule, 該類可以通過nuget包搜索 ABP 安裝。
下面演示在應用程序或類庫中, 定義一個模塊:
public class ApplicationModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(ApplicationModule).GetAssembly());
}
}
說明: 關於IocManager.RegisterAssemblyByConvention的作用, 則是將當前程序集模塊注冊到容器當中, 作為一個模塊, 常見的是暴露模塊對應的服務,
而其中所有的服務, 都是按照聲明周期而聲明, 例如: ITransientDependency ,ISingletonDependency。
下面展示了IocManager.RegisterAssemblyByConvention 執行的部分細節:
public void RegisterAssembly(IConventionalRegistrationContext context)
{
//Transient
context.IocManager.IocContainer.Register(
Classes.FromAssembly(context.Assembly)
.IncludeNonPublicTypes()
.BasedOn<ITransientDependency>()
.If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
.WithService.Self()
.WithService.DefaultInterfaces()
.LifestyleTransient()
);
//Singleton
context.IocManager.IocContainer.Register(
Classes.FromAssembly(context.Assembly)
.IncludeNonPublicTypes()
.BasedOn<ISingletonDependency>()
.If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
.WithService.Self()
.WithService.DefaultInterfaces()
.LifestyleSingleton()
);
//...
}
常見的方法
在AbpModule中, 定義了幾組方法, 分別在應用程序模塊加載的前后進行, 如下:
public virtual void Initialize();
public virtual void PostInitialize();
public virtual void PreInitialize();
public virtual void Shutdown();
- Initialize : 通常, 這里用於注冊程序集依賴選項
- PostInitialize : 初始化最后調用
- PreInitialize : 初始化之前調用
- Shutdown : 當應用程序關閉時調用
模塊依賴
通常來講, 一個模塊往往依賴與一個或者多個模塊, 這里, 也涉及到了模塊的加載生命周期。
假設: 模塊A依賴於模塊B, 那么意味着模塊B會先於模塊A初始化。
關於模塊之間的依賴, 則可以通過特性的方式 DependsOn 為模塊顯示聲明, 如下所示:
[DependsOn(typeof(BModule))]
public class AModule : AbpModule
{
public override void Initialize()
{
//...
}
}
模塊加載
任何模塊都依賴於啟動模塊進行加載, 這很常見, 例如機箱中的各個模塊: 內存、硬盤、顯卡、電源。 都需要通電的過程, 讓他們進行整個啟動過程。
Abp 則依賴於 AbpBootstrapper 來進行調用初始化, 可以通過 Initialize 方法加載。
public static class ApplicationBootstrapper
{
public static AbpBootstrapper AbpBootstrapper { get; private set; }
public static void Init(){
//...
AbpBootstrapper.Initialize();
}
}
同樣, 模塊也可以讀取指定文件夾路徑的方式進行加載模塊, 如下所示:
services.AddAbp<MyStartupModule>(options =>
{
options.PlugInSources.Add(new FolderPlugInSource(@"C:\MyPlugIns"));
});
or
services.AddAbp<MyStartupModule>(options =>
{
options.PlugInSources.AddFolder(@"C:\MyPlugIns");
});