创建自己的模块

时间:2022-01-04 00:41:26

本篇文章介绍怎么创建自己的模块,并且使用依赖注入方法进行模块间的无缝结合。

我们创建一下自己的一个会员模块,针对不同的系统都可以用。你们可以看看我是怎么做的,或者从中得到启发。

目录

1.开始创建项目

2.新建自己的模块

1)引入类库

2)创建模块类

3)创建实体类与仓储

4)创建service类

5)创建对外用的类(接口)

3.其他模块调用会员模块


1.开始创建项目

首先,我们到ABP官网上下载一个MVC NLayered的解决方案。项目名字叫TestMember

具体怎么下载网上很多资料,这里不一一介绍。

2.新建自己的模块

下载完项目之后,我们新建一个类库,名字叫ClassLibraryMember。用户我们的会员模块。

创建完成之后,如下:

创建自己的模块

1)引入类库

Install-Package Abp -Version 2.0.2
Install-Package Abp.Zero -Version 2.0.1

当然,你也可以引入自己想要的版本。我们这里用到Zero模块,你也可以不用。

2)创建模块类

首先我们要创建一个模块类,因为ABP是用模块方式的架构来解耦的。模块之间有依赖性,A模块可以依赖于B模块,B模块依赖于A模块。

模块是怎么工作的呢?

我们可以看到,在Web模块里面,有个模块类,叫XXXWebModule,在App_Start文件夹下。在类的上面,有模块的所有依赖:

[DependsOn( typeof(AbpWebMvcModule), typeof(TestMemberDataModule), typeof(TestMemberApplicationModule), typeof(TestMemberWebApiModule), typeof(ClassLibraryMember.ClassLibraryMemberModule))] public class TestMemberWebModule : AbpModule

ClassLibraryMemberModule模块是作者自己添加进去的,后面再做阐述。

我们看到,首先依赖于AbpWebMvcModule模块,此模块是ABP写的。

然后依赖于TestMemberDataModule模块,此模块是EntityFramework模块的模块类。

然后依赖于TestMemberApplicationModule模块,此模块是Application模块的模块类。

再依赖于TestMemberWebApiModule模块,此模块是WebApi模块的模块类。

最后是自己的模块类(会员模块)ClassLibraryMemberModule。

本次关于模块的调用关系先介绍到这里,有深入兴趣的话,可以看此文章

现在,我们创建自己的模块类,叫ClassLibraryMemberModule,代码如下:

using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Abp.Dependency; using Abp.Modules; namespace ClassLibraryMember { public class ClassLibraryMemberModule:AbpModule { // // 摘要: // This method is used to register dependencies for this module. public override void Initialize() { //这行代码的写法基本上是不变的。它的作用是把当前程序集的特定类或接口注册到依赖注入容器中。 IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly()); } // // 摘要: // This method is called lastly on application startup. public override void PostInitialize() { } // // 摘要: // This is the first event called on application startup. Codes can be placed here // to run before dependency injection registrations. public override void PreInitialize() { } // // 摘要: // This method is called when the application is being shutdown. public override void Shutdown() { } } }

可以看到,我们的会员模块,暂时没依赖到其他模块。

这行代码的写法基本上是不变的。它的作用是把当前程序集的特定类或接口注册到依赖注入容器中:

IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

到此我们的模块以及创建成功了。

我们在梳理一下模块的内部调用顺序:

假如模块A依赖于模块B,在项目启动时则运行方法顺序如下:

模块B的PreInitialize –> 模块A的PreInitialize

模块B的Initialize —> 模块A的Initialize

模块B的PostInitialize—> 模块A的PostInitialize

如果项目停止,则:

模块B的Shutdown—> 模块A的Shutdown

3)创建实体类与仓储

我们创建一个实体Member,继承AbpUser,如下: