本节目录
Abp介绍
学习了一段时间的Abp,领略了一下前辈的架构.总结还是SOLID,降低耦合性.
虽然从架构上说甚至不依赖于DI框架,但实际上在基础框架中还是有一定的必须依赖Castle Windsor.
Abp依靠IOC和AOP实现了大量的自动化.
其中Module设计,是Abp的核心.
Abp源码分析
Abp的入口:AbpBootstrapper.Initialize()
此方法中做了各种配置的注册及初始化.
最重要的是AbpModuleManager的初始化.
在这个初始化代码中
先查询出所有的module,根据依赖关系排序后.并保证AbpKernelModule为第一.
然后初始化module,所有module依次调用PreInitialize、Initialize、PostInitialize
代码实现
定义AbpModule
public class AbpModule { public virtual void PreInitialize() { } public virtual void Initialize() { } public virtual void PostInitialize() { } }
定义2个module
public class ApplicationModule : AbpModule { public override void PreInitialize() { Console.WriteLine("ApplicationModule's PreInitialize is called"); } public override void Initialize() { Console.WriteLine("ApplicationModule's Initialize is called"); } public override void PostInitialize() { Console.WriteLine("ApplicationModule's PostInitialize is called"); } } public class CoreModule : AbpModule { public override void PreInitialize() { Console.WriteLine("CoreModule's PreInitialize is called"); } public override void Initialize() { Console.WriteLine("CoreModule's Initialize is called"); } public override void PostInitialize() { Console.WriteLine("CoreModule's PostInitialize is called"); } }
定义IoCManager
public class IocManager { public static IocManager Instance { get; private set; } public IWindsorContainer IocContainer { get; private set; } static IocManager() { Instance = new IocManager(); } public IocManager() { IocContainer = new WindsorContainer(); //Register self! IocContainer.Register( Component.For<IocManager>().UsingFactoryMethod(() => this) ); } }
实现AbpBootstrapper
public class AbpBootstrapper { public IocManager IocManager { get; private set; } public AbpBootstrapper() { IocManager = IocManager.Instance; } public virtual void Initialize() { InitializeModules(); } private void InitializeModules() { var types = Assembly.GetExecutingAssembly().GetTypes(); var moduleTypes = new List<Type>(); var modules = new List<AbpModule>(); foreach (var type in types) { if (typeof(AbpModule).IsAssignableFrom(type)) { moduleTypes.Add(type); IocManager.IocContainer.Register(Component.For(type)); } } foreach (var module in moduleTypes) { var obj = IocManager.IocContainer.Resolve(module) as AbpModule; modules.Add(obj); } modules.ForEach(x => x.PreInitialize()); modules.ForEach(x => x.Initialize()); modules.ForEach(x => x.PostInitialize()); } }
执行
class Program { static void Main(string[] args) { var booter = new AbpBootstrapper(); booter.Initialize(); Console.ReadKey(); } }
Abp原理如上,只是在本例中并未做dependency排序处理.
在Abp中的排序依赖ListExtensions类对List的扩展方法实现的.
本文地址:http://neverc.cnblogs.com/p/5249103.html