abp模块生命周期设计思路剖析

2020-02-12 11:32:48 浏览数 (1)

abp中将生命周期事件抽象为4个接口:

代码语言:javascript复制
//预初始化
public interface IOnPreApplicationInitialization
{
    void OnPreApplicationInitialization([NotNull] ApplicationInitializationContext context);
}

//初始化
public interface IOnApplicationInitialization
{
    void OnApplicationInitialization([NotNull] ApplicationInitializationContext context);
}

//初始化完成
public interface IOnPostApplicationInitialization
{
    void OnPostApplicationInitialization([NotNull] ApplicationInitializationContext context);
}

//关闭
public interface IOnApplicationShutdown
{
    void OnApplicationShutdown([NotNull] ApplicationShutdownContext context);
}

abp定义了一个模块生命周期接口,该接口只有两个方法,用于初始化和关闭。

代码语言:javascript复制
public interface IModuleLifecycleContributor : ITransientDependency
{
    void Initialize([NotNull] ApplicationInitializationContext context, [NotNull] IAbpModule module);

    void Shutdown([NotNull] ApplicationShutdownContext context, [NotNull] IAbpModule module);
}

这个接口的参数是IAbpModule接口的类型,也就是派生自AbpModule的模块类型。该接口有一个默认实现,是一个抽象类,主要是用于复用。

代码语言:javascript复制
public abstract class ModuleLifecycleContributorBase : IModuleLifecycleContributor
{
    public virtual void Initialize(ApplicationInitializationContext context, IAbpModule module)
    {
    }

    public virtual void Shutdown(ApplicationShutdownContext context, IAbpModule module)
    {
    }
}

abp根据四个生命周期分别有四个类型,这四个类型是基于模块生命周期基类创建的。

代码语言:javascript复制
public class OnApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase
{
    public override void Initialize(ApplicationInitializationContext context, IAbpModule module)
    {
        (module as IOnApplicationInitialization)?.OnApplicationInitialization(context);
    }
}

public class OnApplicationShutdownModuleLifecycleContributor : ModuleLifecycleContributorBase
{
    public override void Shutdown(ApplicationShutdownContext context, IAbpModule module)
    {
        (module as IOnApplicationShutdown)?.OnApplicationShutdown(context);
    }
}

public class OnPreApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase
{
    public override void Initialize(ApplicationInitializationContext context, IAbpModule module)
    {
        (module as IOnPreApplicationInitialization)?.OnPreApplicationInitialization(context);
    }
}

public class OnPostApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase
{
    public override void Initialize(ApplicationInitializationContext context, IAbpModule module)
    {
        (module as IOnPostApplicationInitialization)?.OnPostApplicationInitialization(context);
    }
}

只有"关闭应用"这个生命周期实现Shutdown方法,其余的都是实现Initialize方法。最后是传入的参数abp模块去调用对应的生命周期。 剖析图如下:

0 人点赞