ASP.NET Core Zero笔记(模块系统)

简介

在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");
});

查看更多

原文地址:https://www.cnblogs.com/zh7791/p/15502528.html