.NET的可重用数据访问层的构建

.NET的可重用数据访问层的构建[20200907153435].txt
作者:王远斌
摘要:有人提出I.种新的数据访问层的N层架构的设计解决方案.它可以解决多种问题,例如:低效率的开发,移植.更新和重用过程中的困难.该解决方案采用了.NET的反射技术和设计模式.这种解决方案的I.种典型应用表明:新的数据访问层的解决方案的性能优于目前的N层架构.更重要的是,应用表明:新的数据访问层的解决方案可以有效地重用.
关键字:N层架构;数据访问层;反射技术;重用
I.引言
在软件开发过程中,软件系统的结构设计I.直发挥着关键的作用.对于大型企业级应用来说,系统架构不仅影响系统设计和系统开发,而且与后续系统开发有直接联系,它甚至可以决定整个系统的开发是否成功.目前,由于其明显的优势,N层架构已经成为I.种标准的构建企业级应用.然而,当前庞大而复杂的N层体系架构出现了I.些问题,例如:低效率的开发,移植.更新和重用过程中的困难.文中提出了.NET技术和N层架构的解决方法,即如何建立I.种新的利用反射和工厂模式的数据访问层.
IIN层架构的采用
N层架构是I.种双层架构的新型软件结构,以便于有效地处理大规模分布应用中的问题.在双层架构中,客户端的数据库和业务逻辑的存储程序是I.个抽象和自我管理的应用逻辑层,这种存储程序也纳入了应用服务器中.通过这种方式,N层架构应运而生.在N层架构中,业务逻辑在应用服务器中,应用服务器中包含了业务规则.数据处理等.N层架构具有以下优点:良好的透明性和封装;高内聚.低耦合;易扩展.易更新.重用性好;便于开发者合作;高效率的开发.
最常见的N层架构有III个不同的层次,包括用户界面.业务逻辑层和数据访问层.用户界面层仅仅是I.种用来处理用户界面应用程序的软件,它的主要任务是实现服务器和客户端的通信.可以是I.个网页,或者是传统的命令提示符界面.这I.层还负责获取用户的数据输入,并将他们传递给业务逻辑层.业务逻辑层包含了业务规则.数据处理等,这层并不知道任何关于HTML及怎样将其输出的信息.它不关心ADO或SQL,这些任务分配它相应的上层或下层来完成.这层的核心职能是接收用户界面的请求.按照有关的业务逻辑处理请求.发送请求并接收相应的结果,将这些结果返回给用户界面层.数据访问层是整个架构的最底层,它为业务逻辑层提供数据服务,在I.些数据存储(关系型数据库和XML等)中存储或检索数据.
III.Net中的反射和工厂模式
III.I..NET中的反射
在.NET中,使用CLR(公共语言运行库)提供反射技术,这种技术可以在运行时获得包含在集合中的信息类型.通常,.NET应用程序包括如下几部分:组件,模块和类型.反射提供了I.种编程方式,并且允许程序员在运行时检查类型信息并对这些类型调用方法.例如,I.个组件是I.个可重用和可自我描述的通用语言运行库应用程序的构件.它可以在运行时加载组件,并获得该组件中的所有类型.
类型是获取元数据的主要手段,可以作为映像API的门户.它提供了多种方法来获取类型声明的信息,如构造函数.属性.方法和事件.方法信息包括方法的信息,可以发现方法的属性,并提供元数据的获取方法.它给出了方法的名称.参数,返回它的值,甚至还可以调用该方法.
通过反射技术,可以实现多种功能,例如:创建I.种类型的实例,将这I.类型与当前的对象绑定以及获得目前对象的类型.当应用程序在运行中为了执行某I.操作需要加载I.个特殊类型时,可以使用反射技术.
III.II工厂模式
伯特兰·迈耶建议软件实体应该是可扩展的,但是不可修改的.GOF(GangofFour:IV人组)的工厂模式在I.定程度上遵守这种原则,并已在软件开发中获得了广泛的应用.工厂模式负责建立有公共接口的类型的实例.通过工厂模式,某些类型的实例可以被动态地创建,而不需要预先了解类型名称的信息.
IV数据访问层的设计
虽然目前流行的几种多层结构(包括III层.IV层和V层)比以往发挥着更为重要的作用,但是,当系统庞大而且数据库复杂时,多层结构的开发似乎仍然很困难.
现有的框架直接采用存储过程或程序中的SQL语句.因此,大量的SQL语句需要组建,使得数据访问层的工作量巨大.效率低,甚至导致移植和更新困难.
.NET的反射技术与工厂模式的结合产生了I.种新的数据访问层的解决方案.在数据库转换时,工厂模式使你可以轻而易举地更新系统.OOP(面向对象的程序设计),开发人员从繁重的工作和复杂的SQL语言中解放了出来.所有的SQL语句将由开发人员熟悉的OOP构建,与此同时,新的数据访问层具有较高的重用性和灵活性,从而避免了过去的无意义而又重复的开发.
这项设计的的原理包括:
I.)使用工厂模式构建数据访问层,以便于克服数据库转换引起的问题;
II)利用反射技术动态构建所需的SQL语句,以避免频繁的.低效的SQL语句编写;
III)引入数据实体层;
IV)引入数据访问子层_框架子层,并实现再利用.
数据访问层的设计如下:
I.)引入数据实体层
在这个解决方案中,通过ORM(对象关系映射),所有的数据实体作为作为I.个单I.的层_数据实体层取出.通过这种方式,对象将被映射到RMDB(关系映射数据库)中.当对数据库执行操作时,程序员就不再需要处理复杂的SQL语句了,它可以像对象I.样被处理.与此同时,数据实体以对象的形式显示数据,并且以消息的形式在层与层之间发送和接收.
II)数据访问层的设计
本解决方案中,数据访问层被分为两个子层,DASL子层和框架子层.这种新型架构的结构如图I.所示.DASL子层不再直接与数据库进行通信,它只负责封装业务逻辑层的请求并将信息传送给下层.框架子层接收上层的请求,然后自动创建所有的SQL语句.该框架子层独立于应用程序,因此可以高度地重复使用.
框架子层的结构如图II所示.具体描述如下:
I.)查询语句
这个类的核心功能是创建SQL语句,以下面的查询语句为例:
SELECTfieldFROMtablenameWHEREconditionORDERBYsort".
由于该表已经被映射到实体类中,诸如字段.表名.条件和排序的变量就可以通过使用.NET的反射技术获得了.
例如,构成SQL语句:‘Select*fromtablenamewherecondition’的构造函数如下:
publicQueryStatement(objectobj)
{
this.dataType=obj.GetType();
this.fields="*";
this.tableName=this.dataType.Name;
this.filter=ParseObjectFilter(obj);
}
正如上面的代码所示,首先,输入对象的类型可以通过反射获得,这样更容易获得表名.其次,在"ParseObjectFilter()"方法中,当前对象的所有字段可以使用反射来构造查询条件字符串.
II)存储管理器
这种类型的主要作用是执行SQL语句.根据输入对象的实例,它通过调用查询语句的方法来形成SQL语句,然后使用ADO.NET执行该语句,并将执行结果返回给上层.
以查询语句‘Select*fromtablenamewherecondition’为例:
publicstaticvoidLoadDataSet(QueryStatementquery,DatasetsdataSet)
{
cmd.CommandText=query.ToString();
adapter.SelectCommand=cmd;
if(adapterisSystem.Data.Common.DbDataAdapter)
{
((DbDataAdapter)adapter).Fill(dataSet,query.DataSetTable);
}
}
应该注意到,输入的对象"query"已包含了构造的SQL语句.
V通告系统应用程序
现在来介绍被称为通告系统的应用程序,它采用了上面提到的数据访问层.这种系统是I.种自动通知和信息采集系统,常在突发事件中被用来自动收集和发出信息,例如灾难恢复和保持事务连续性.这I.系统的原理如图III所示.
该系统的功能包括通知快速行动部分.调动快速行动组.更新管理系统.达到警戒线时预警并发送预警信息,以及发送信息和指令.
应用程序在.NET平台上开发,开发语言采用C#,数据库操作系统是SQLServerII000,系统B/S构建,用户接口使用ASP.NET开发.图I.中所示的N层架构被采用了,即在原来系统中使用的被证明是正确和可靠的架构被直接引入了该系统.
由于包含框架子层,数据访问层的采用简化了数据实体层的封装,使开发人员摆脱了数据实体层的封装,允许面向对象的数据库操作,这种操作让开发人员从处理复杂SQL语句中解放了出来.另外,由于这层的高度重用性,开发过程被缩短,开发效率明显提高.
VI结论
文中介绍了I.种新的数据库访问层设计解决方案,该方案采用了反射技术和设计模式.这种解决方案适用于典型的系统并且执行良好.
致谢
非常感谢重庆大学的王晶.蔡华和徐红的帮助.
参考文献
I.ZhangP,TangF,LinG.软件架构设计在XP中的实施[J].计算机工程与应用,II00III,IIIIX(IIIIII):I.0VI-I.0IX.
IISimonR,OllieC.C#高级编程[M].第I.版.北京:清华大学出版社,II00II:IIIIIIIX-IIIIVVIII.
IIIYanH.Java与模式[M].第I.版.北京:电子工业出版社,II00IV.I.IIVII-II0VI.
IVXuH,XuL..NET的信息管理系统[J].武汉工程,II00III,I.V(II):IIIIX-IVI..
VWangY,ChenP.反射技术与软件的适应性[J].计算机工程与设计,II00III,IIIV(I.0):IIVI-IIIX.
VIXuW,HeJ,ZhangJ,etal.反射技术的动态界面的实现[J].计算机工程与设计,II00III,IIIV(I.0):VVII-VIX.
VIIHuY,PengL,ChiC..NET的III层架构设计[J].计算机工程与设计,II00III,IIIX(VIII):I.VIIIII-I.VIIV.
附件II:外文原文(复印件)
Constructionofareusabledataaccesslayerbasedon.NET
WANGYuan-bin
Abstract:AnewdesignsolutionofdataaccesslayerforN-tierarchitectureispresented.Itcansolvetheproblemssuchaslowefficiencyofdevelopmentanddifficultiesintransplantationupdateandreuse.Thesolutionutilizesthereflectiontechnologyof.NETanddesignpattern.AtypicalapplicationofthesolutiondemonstratesthatthenewsolutionofdataaccesslayerperformsbetterthanthecurrentN-tierarchitecture.Moreimportantly,theapplicationsuggeststhatthenewsolutionofdataaccesslayercanbereusedeffectively.
Keywords:N-tierarchitecture;dataaccesslayer;reflectiontechnology;reuse
I.Introduction
Inthecourseofsoftwaredevelopment,thearchitecturedesignofsoftwaresystemplaysakeyroleallthetime.Forlargeenterpriseapplication,thesystemarchitecturecaninfluencenotonlythesystemdesignandthesystemdevelopment,butalsothefollow-updevelopmentofthesystemdirectly.Itcanevendeterminewhetherthewholesystemdevelopmentissuccessful.Currently,becauseofitsobviousadvantages,N-tierarchitecturehasalreadybecomeastandardofstructuringenterpriseapplication.However,atpresent,theenormousandcomplexN-tierarchitecturehassomeproblems,suchaslowefficiencyofdevelopment,anddifficultiesintransplantation,updateandreuse.Basedon.NettechnologyandN-tierarchitecture,thispaperputsforwardasolutiontohowtobuildanewdataaccesslayerbyutilizingreflectionandfactorypattern.
IIIntroductionofN-tierarchitecture
N-tierarchitectureisanewkindofsoftwarearchitecturebasedontwo-tierarchitectureinordertodealwiththeproblemsoflargescaledistributionapplicationseffectively.Thestorageprocedureofdatabaseandbusinesslogicofaclientintwo-tierarchitectureisanabstractedandself-governedapplicationlogicallayer,whichisincorporatedintheapplicationserver.Inthisway,N-tierarchitecturecomesintobeing.InN-tierarchitecture,businesslogicisinapplicationserver.Applicationservercontainsbusinessrules,datamanipulation,etc.ThisN-tierarchitecturehasthefollowingadvantages:goodtransparentandencapsulation;highcohesivenessandlowcoupling;easytoexpand,updateandreuse;convenientfordeveloperstocooperate;andimprovedefficiencyfordevelopment.
ThemostcommonlyN-tierarchitecturehasthreedistinctlayers,includinguserinterface,businesslogicallayeranddataaccesslayer.Auserinterfacelayerisonlyapieceofsoftwarethatdealswiththeuserinterfaceofanapplication.Thislayerisresponsibleforthecommunicationbetweentheserverandclient.Itcanbeawebpageoratraditionalorderpromptinterface.Thislayerisalsoresponsibleforaccessingthedataauserinputsandtransmittingthemtothebusinesslogicallayer.AbusinessLogicLayercontainsthebusinessrules,datamanipulation,etc.ThislayerdoesnotknowanythingaboutHTMLandhowtooutputit.ItdoesnotcareaboutADOorSQL.Thosetasksareassignedtoeachcorrespondinglayeraboveorbelowit.Thecorefunctionsofthelayerareacceptingrequestfromtheuser’sinterface,dealingwiththerequestaccordingtorelevantbusinesslogic,sendingoutrequestandreceivingcorrespondingresultandreturningtheresulttotheuserinterfacelayer.Thedataaccesslayeristhebottomlayerofthewholearchitecture,whichprovidesthebusinesslogiclayerwithdataservices,andstoresorretrievesdatainsomedatastore(RDBMS,XMLetc.).
IIIReflectionin.NETandfactorypattern
III.I.Reflectionin.NET
In.NET,CLR(commonlanguageruntime)providesreflectiontechnologybywhichinformationabouttypescontainedinanassemblyatruntimecanbeobtained.Usually,applicationsin.NEThaveseveralpartsasfollows:assemblies,modulesandtypes.Reflectionprovidesakindofprogrammingway,andallowsaprogrammertoinspecttypeinformationandinvokemethodsonthosetypesatruntime.Forexample,anassemblyisareusableandselfdescribingbuildingblockofaCommonLanguageRuntimeapplication.Itcanloadassemblyatruntime,andgetallthetypesinthatassembly.TypeistheprimarymeansbywhichmetadatacanbeaccessedanditactsasagatewaytoreflectionAPI.Itprovidesmethodsforobtaininginformationaboutatypedeclaration,suchastheconstructors,properties,methodsandevents.MethodInformation,includingtheinformationofamethod,discoverstheattributesofamethodandprovidesaccesstomethodmetadata.Itprovidesthename,theparametersofamethod,returnsitsvalue,andevencallsit.
Throughthereflectiontechnology,manyfunctionscanberealized,suchascreatinginstanceofatype,bindingthetypetoacurrentobjectandobtainingthetypefromacurrentobject.Reflectioncanbeusedwhentheapplicationprogramneedtoloadonespecialtypeatruntimeinordertoimplementatask.
III.IIFactorypattern
BertrandMeyerproposedthatsoftwareentitiesshouldbeopenforextension,butcloseformodification.GOFsFactoryPatterncompliedwiththeprincipletoacertaindegreeandhasalreadywonextensiveapplicationinsoftwaredevelopment.Factorypatternisresponsibleforbuildingtheinstanceoftypewhichhasthecommoninterface.Throughfactorypattern,theinstanceofsometypecanbedynamicallycreated,withoutinformationabouttypenameinadvance.
IVDesignofdataaccesslayer
Thoughseveralkindsofmulti-tierframeworksthatprevailatpresent(includingIII-tier,IV-tier,andV-tier)haveplayedagreaterrolethanever,thedevelopmentofmulti-tierstillseemsdifficultwhenasystemishugeandthedatabaseiscomplicated.TheexistingframeworkadoptsthestoreprocedureorSQLsentencesintheprogramdirectly.Hence,alargenumberofSQLsentencesneedtobeconstructed,whichmaketheworkloadofdataaccesslayerenormousandinefficient,evencausedifficultiesintransplantationandupdate.
Combiningthereflectiontechnologyof.NETwithfactorypatterngivesrisetoanewsolutionofdataaccesslayer.Factorypatternofferseasyupdatetothesystemwhenthedatabaseisswitched.BasedonOOP,thedevelopersareliberatedfromheavyworkandcomplicatedSQLlanguage.AlloftheSQLsentenceswillbebuiltupbyOOPwithwhichadeveloperisfamiliar.Meanwhile,thenewdataaccesslayerisofhighreuseandflexibility.Itavoidsmeaninglessandrepeateddevelopmentinthepast.
ThePhilosophyofdesigninvolves
I.)Usingthefactorypatterntoconstructthedataaccesslayersoastoovercometheproblemscausedbydatabaseswitching;
II)UtilizingreflectiontechnologytoconstructrequiredSQLsentencesdynamicallytoavoidthefrequentandinefficientwriteofSQLsentences;
III)Importingthedataentitylayer;and
IV)Importingthedataaccesssublayer-frameworksublayer,andrealizethereuse.
Thedataaccesslayerisdesignedasfollows.
I.)Importthedataentitylayer
Inthissolution,throughORM(Object-RelationalMapping),alldataentitiesaretakenoutasasinglelayer,dataentitylayer.Inthisway,objectswillbe,mappedtoRMDB.Whenmanipulatedatabase,programmersdonotneedtodealwithcomplicatedSQLsentencesanymore.Itcanbehandledlikeanobject.Meanwhile,thedataentitiesdisplaythedataintheformofobject.Theyaresentandreceivedasmessagesbetweenlayers.
II)Designofthedataaccesslayer
Inthissolution,dataaccesslayerisdividedintotwosublayers,DASLsublayerandframeworksublayer.ThestructureofthisnewarchitectureisillustratedinFig.I..NowDASLsublayernolongercommunicateswithdatabasedirectly.ItonlyencapsulatestherequestfromBLlayerandsendsmessagetoalowerlayer.Theframeworksublayerreceivestherequestfromupperlayer,andthenbuildsallSQLsentencesautomatically.Theframeworksublayerisindependentfromapplication,socanbehighlyreused.
ThestructureoftheframeworksublayerisillustratedinFig.II,anddescribedbelow.
I.)QueryStatement
ThecorefunctionofthisclassistobuildSQLsentences.Takeaquerysentenceforexample:
SELECTfieldFROMtablenameWHEREconditionORDERBYsort".
Becausethetableshavebeenmappedtoentityclasses,variablessuchasfield,tablename,conditionandsort,canbeobtainedbyusingthereflectionof.NET.
Forexample,theconstructionfunctionwhichconstructstheSQLsentence‘Select*fromtablenamewherecondition’islikethis:
publicQueryStatement(objectobj)
{
this.dataType=obj.GetType();
this.fields="*";
this.tableName=this.dataType.Name;
this.filter=ParseObjectFilter(obj);
}
Astheabovecodeshows,firstly,thetypeofinputobjectcanbegottenbyusingthereflection,whichmakesiteasytogetthetablename.Secondly,inmethod‘ParseObjectFilter()’,allfieldsofcurrentobjectareobtainedbyutilizingreflectiontoconstructthequeryconditionstring.
II)Persistencemanager
TheprincipalfunctionofthistypeistoexecuteSQLsentences.Accordingtotheinstanceofinputobject,itformsSQLsentencesbycallingthemethodofquerystatements,thenexecutesSQLsentencesbyusingADO.NETandreturnstheresulttotheupperlayer.
Takethequerysentence‘Select*fromtablenamewherecondition’forexample:
publicstaticvoidLoadDataSet(QueryStatementquery,DataSetdataSet)
{
cmd.CommandText=query.ToString();
adapter.SelectCommand=cmd;
if(adapterisSystem.Data.Common.DbDataAdapter)
{
((DbDataAdapter)adapter).Fill(dataSet,query.DataSetTable);
}
}
Itshouldbenoticedthattheinputobject’query’hasincludedconstructedSQLsentence.
VApplicationtoanotificationsystem
Anapplication,knownasnotificationsystem,ispresentedhere.Itutilizesthedataaccesslayermentionedabove.Thesystemisanauto-notificationandinformationcollectingsystemwhichisusedtocollectandsendinformationautomaticallyinthecasesofsuddenevents,suchasdisasterrecoveryandkeepingtransactioncontinuity.TheprincipleofthesystemisshowninFig.III.
Thefunctionsofthesystemincludesinformingthequickactiondepartment,dispatchingthequickactiongroup,updatingthemanagementsystem,forewarningandsendingforewarninginformationinthewarningline,andsendingmessagesandinstructions.
Theapplicationwasdevelopedonthe.NETplatform.ThedevelopmentlanguageisC#.TheDBMSisSQLServerII000.ThesystemwasconstructedbasedonB/SandUIwasdevelopedbyASP.NET.TheN-tierarchitectureshowninFig.I.wasadopted.Framework,whichwasusedintheformersystemandprovedcorrectandreliable,wasdirectlyimportedtothesystem.
Withtheframeworksub-layer,theadoptionofthedataaccesslayersimplifiestheencapsulationofthedataentitylayer,freesthedeveloperfromtheencapsulationofthedataentitylayerandallowsorient-objectedmanipulatingofthedatabase,whichreleasesdevelopersfromhandlingcomplicatedSQLsentences.Thesebenefitthedebug,modificationanddevelopmentofthesystem.Inaddition,asthelayerisofhighreuse,thedevelopingcourseisshortenedandtheefficiencyisenhancedobviously.
VIConclusions
Inthisarticle,anewdesignsolutionofdatabaseaccesslayerispresentedbyutilizingthereflectiontechnologyanddesignpattern.Thesolutionwasappliedtothetypicalsystemandperformswell.
Acknowledgements
TheauthorsaregratefultoWangjing,CaihuaandXuhongfromChongqingUniversityfortheirhelpinthearticle.
References
I.ZhangP,TangF,LinG.ImplementofsoftwarearchitecturedesigninXP[J].ComputerEngineering&Applications,II00III,IIIIX(IIIIII):I.0VI-I.0IX.
IISimonR,OllieC.ProfessionalC#[M].I.sted.Beijing:TsinghuaUniversityPress,II00II:IIIIIIIX-IIIIVVIII.(inChinese).
IIIYanH.JavaandPattern[M].I.sted.Beijing:PublishingHouseofElectronicsIndustryII00IV.I.IIVII-II0VI.(inChinese).
IVXuH,XuL.Informationmanagementsystembasedon.NET[J].JournalofWuhanEngineeringInstitute,II00III,I.V(II):IIIIX-IVI..
VWangY,ChenP.Reflectionandtheadaptationofsoftware[J].ComputerEngineering&Design,II00III,IIIV(I.0):IIVI-IIIX.
VIXuW,HeJ,ZhangJ,etal.Implementofdynamicalinterfacebasedonreflectiontechnology[J].ComputerEngineering&Design,II00III,IIIV(I.0):VVII-VIX.
VIIHuY,PengL,ChiC.DesignofThree-tierarchitecturebasedon.NET[J].ComputerEngineering&Design,II00III,IIIX(VIII):I.VIIIII-I.VIIV.

版权保护: 本文由 hbsrm.com编辑,转载请保留链接: www.hbsrm.com/lwqt/wxzs/85.html

好棒文