NopCommerce為了實現(xiàn)松耦合的框架設(shè)計目的,使用了IOC框架:Autofac。據(jù)有人測試,Autofac是性能很好的IOC工具。
1、在IOC中,組件首先需要在IOC中注冊,有通過配置文件注冊的。像Spring.net,也有通過特性注冊的,像StructureMap,也有通過代理來注冊的,像Autofac。但是IOC講究一個原則,就是接口和實現(xiàn)分離。所有IOC就是生命某個具體類實現(xiàn)了某個接口。然后在使用時,系統(tǒng)從IOC中獲取接口的實現(xiàn)類,并創(chuàng)建對象。
2、下面來看NopCommerce如何使用Autofac實現(xiàn)松耦合的框架設(shè)計的。其實它的插件機制也是通過Autofac來實現(xiàn)的。
IOC的封裝及靈活使用機制主要在Nop.Core.Infrastructure中封裝的。在Autofac中,對象又稱為組件。組件生命周期分為:單例、臨時和生命周期域內(nèi),如下定義:
namespace Nop.Core.Infrastructure.DependencyManagement { public enum ComponentLifeStyle { Singleton = 0, Transient = 1, LifetimeScope = 2 } } Autofac中有容器、并提供方法注冊接口及其類型,還提供方法查找到注冊的類型,以及自動創(chuàng)建對象。
3、類型查找器
為了支持插件功能,以及支持一些自動注冊的功能。系統(tǒng)提供了類型查找器。ITypeFinder以及實現(xiàn)類就是提供此功能。通過類型查找器可以查找本程序域中的類,也可以查找整個bin目錄下所有動態(tài)鏈接庫中類,并把它們注冊到類型反轉(zhuǎn)容器中。ITypeFinder以及實現(xiàn)類如下:
4、類型注冊
容器管理類:ContainerManager,管理通過Autofac生成的容器;
容器配置器:ContainerConfigurer:配置依賴反轉(zhuǎn)容器,建立整個框架的類型依賴注冊和類型查找類之間的關(guān)系。
在系統(tǒng)中有一個依賴類引擎上下文環(huán)境:EngineContext,可以根據(jù)配置文件生成引擎,此引擎是負責(zé)根據(jù)類型接口從容器中返回對象。
系統(tǒng)默認引擎NopEngine,若沒有配置有效的引擎,即用默認引擎,生成的引擎保存在單例容器中。
它們的關(guān)系如下:
系統(tǒng)在類MvcApplication的方法Application_Start中初始化引擎上下文。并通過調(diào)用EngineContext.Initialize(false);實現(xiàn)所有反轉(zhuǎn)依賴的注冊功能;
5、容器注冊類
系統(tǒng)注冊接口為:IDependencyRegistrar,系統(tǒng)通過ContainerConfigurer注冊此接口以及實現(xiàn)類的,并通過ITypeFinder類搜尋程序集里實現(xiàn)接口IDependencyRegistrar的類。代碼如下:
namespace Nop.Core.Infrastructure.DependencyManagement { /// <summary> /// Configures the inversion of control container with services used by Nop. /// </summary> public class ContainerConfigurer { public virtual void Configure(IEngine engine, ContainerManager containerManager, EventBroker broker, NopConfig configuration) { //other dependencies containerManager.AddComponentInstance<NopConfig>(configuration, "nop.configuration"); containerManager.AddComponentInstance<IEngine>(engine, "nop.engine"); containerManager.AddComponentInstance<ContainerConfigurer>(this, "nop.containerConfigurer"); //type finder containerManager.AddComponent<ITypeFinder, WebAppTypeFinder>("nop.typeFinder"); //register dependencies provided by other assemblies var typeFinder = containerManager.Resolve<ITypeFinder>(); containerManager.UpdateContainer(x => { var drTypes = typeFinder.FindClassesOfType<IDependencyRegistrar>(); var drInstances = new List<IDependencyRegistrar>(); foreach (var drType in drTypes) drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drType)); //sort drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList(); foreach (var dependencyRegistrar in drInstances) dependencyRegistrar.Register(x, typeFinder); }); //event broker containerManager.AddComponentInstance(broker); } } }
新聞熱點
疑難解答
圖片精選