您的位置:首页 > 移动开发 > Objective-C

MS 的IOC容器(ObjectBuilder)?

2005-11-26 11:12 316 查看
MS的NetFramework2.0的EnterpriseLibrary-November2005CTP和CompositeUserInterface(UI)ApplicationBlock都是依赖于一个核心的组件ObjectBuilder。它同时实现了两个重要的设计模式ServiceLocator模式和DependencyInjection模式,是一个IOC容器。ObjectBuilder可以作为一个IOC框架开发,EnterpriseLibrary-November2005CTP的各个模块之间的依赖关系相比较他的以前的版本大大减弱。

“依赖注入”(DependencyInjection)设计模式和“服务定位器”(ServiceLocator)设计模式的目标:应该将组件的配置与使用分离开。

"依赖注入”(DependencyInjection)来自IOC容器中,在DotNet底下现在比较著名的就是Castle和Spring.net。依赖注入的形式主要有三种,我分别将它们叫做构造子注入(ConstructorInjection)、设值方法注入(SetterInjection)和接口注入(InterfaceInjection)。ObjectBuilder实现了构造子注入(ConstructorInjection)、设值方法注入(SetterInjection)。

“服务定位器”(ServiceLocator)模式模式背后的基本思想是:有一个对象(即服务定位器)知道如何获得一个应用程序所需的所有服务。

下面是ObjectBuilder的具体介绍:

ObjectBuilder

TheObjectBuilderisanewsubsystemthatissharedbetweenEnterpriseLibraryandtheCompositeUserInterface(UI)ApplicationBlock.EnterpriseLibraryusestheObjectBuildersubsystemfortaskssuchasinjectingconfigurationintoblockclassesandconnectinginstrumentationclassestoapplicationblocks.

TheCompositeUIApplicationBlockusesacustomunderlyingsystemcalledObjectBuildertoinjectinstancesofobjectsoftheappropriatetypeandwithpresetpropertiesintotheapplicationatruntime.

DesignofObjectBuilder

Theconstructionanddisposalofobjectinstancesisacommonprocessinmostapplications,andparticularlyinbusinessapplicationssuchasthosebuiltusingtheCompositeUIApplicationBlockandtheEnterpriseLibrary.Forthisreason,theseblockstakeadvantageofanunderlyingsub-systemcalledObjectBuilderthatperformsalloftherepetitiveandnecessarytasksforcreatingobjectinstances,whilestillprovidingahighlevelofflexibility.

ObjectBuilderencapsulatesfeaturesthatsimplifythecreationofobjectinstances.Itcan:

Ensurethecreationofspecificconcreteclassinstances,evenwhenrequestsareforabstracttypes.
Ensurethereturnofexistingobjectinstanceswhenthisisappropriate,oralwaysgeneratenewinstances.
Createtheappropriateobjectsfromfactoryclassesbasedonconfigurationdata.
Intelligentlyselecttheappropriateconstructorwhenaclassexposesmorethanoneconstructor.
Applyvaluestopublicpropertiesautomatically,andexecutemethodsontheobject,inresponsetopre-definedpolicies.
Respondtoattributesdeclaredonthepropertiesandmethods,whichinfluencethecreationandnamingofthenewobject.
CommunicateautomaticallywithobjectsthatsupporttheIBuilderAwareinterfacetoindicatethatobjectcreationiscomplete.
Provideateardownfacilitythatcanremovesettingsfromexistingobjectsbyreversingthechainofoperations.

ObjectBuilderisalow-levelutilitythat,inmostcases,youwillnotinteractwithdirectlyinyourapplications.Theclassesintheapplicationblocksuseittogenerateobjectinstancesinresponsetoyourcodecreatingtheclassesdeclaredwithintheapplicationblocks.

However,youcanusethefeaturesofObjectBuilderdirectlyinyourapplicationsandyourownframeworksifyouwish.YoucanalsoinfluencethebehaviorofObjectBuilderbycreatingyourownstrategiesormodifyingtheexistingstrategies.

Note:

ObjectBuilderisapatterns&practicesApplicationBlock,but-duetothehighlyspecificaudiencethatittacklesanditsrecentinception-isnotyetfullydocumentedasastand-aloneassetlikeEnterpriseLibraryapplicationblocksortheCompositeUIApplicationBlock.

ObjectBuilderArchitecture

ObjectBuilderusesapipelineofstrategiesthatallowsmultipleoperationstotakeplaceasobjectsareinstantiatedandpreparedforuse.Thisallowsyoutocontroltheorderthattheprocessestakeplace.Italsosupportscontrolleddisposalofobjectinstancesbyexecutingtheappropriatepipelineprocessesinthereverseorder.

ObjectBuilderstrategiesmanagetheprocessesperformedonobjectsduringconstructionanddisposal.TheObjectBuilderpipelineisorganizedintostages,andeachstageofthepipelinecontainsmultiplestrategies.Youcanimplementyourownstrategiesasa.NETclasswithaspecificinterface.

ObjectBuilderMethods

ObjectBuilderresidesinthenamespaceMicrosoft.Practices.ObjectBuilder,andthebaseclassBuilderBaseexposestwomethods.TheBuildUpmethodhastwooverloads:

[C#]

CopyCode

BuildUp(locator,type,id,instance,policies[]);
BuildUp<type>(locator,id,instance,policies[]);
where:

locatorisareferencetoaclassthatimplementstheIReadWriteLocatorinterface,andwhichprovideshintsastothelocationoftheobjectorclass.Formoreinformation,see"UsingaReadWriteLocator"laterinthistopic.
typeisthetypeofobjecttocreate.
idistheidentifiertoassigntothenewobjectinstance.
instanceisanoptionalreferencetoanexistingobjectinstanceuponwhichthepipelineprocesswillact.Thisallowsyoutotakeexistingobjectsandensurethattheyareproperlypreparedforusebypassingthemthroughthepipeline.ObjectBuilderappliesonlytheappropriateprocessestosuchobjectinstances.
policies[]isanarrayofPolicyListinstancesthatimplementtransientpoliciesthatover-ridethebuilt-inpolicies.Formoreinformation,see"UsingaPolicyList"laterinthistopic.

TheTearDownmethodtakesanexistingobjectinstanceandrunsitbackthroughthestrategychain.ThisprocesscanremovefeaturesaddedtotheobjectduringtheBuildUpprocessifyouwanttore-usetheobject.YoudonothavetocalltheTearDownmethodonobjectsthatyounolongerneedtouse.

ThesignatureoftheTearDownmethodis:

[C#]

CopyCode

TearDown<type>(instance);
where:

typeisthetypetoun-build.Ifnotprovided,ObjectBuilderinfersthisfromthetypeofobjectpassedastheinstanceparameter.
instanceisareferencetoanexistingobjectinstanceuponwhichthepipelineprocesswillactinreverse.

UsingaReadWriteLocator

ObjectBuilderusestheconceptofalifetimecontainertostoreobjectreferences,whichensuresthecorrectmanagementofobjectsandtheirdisposalatthecorrecttimes.Locatorsreferenceindividualobjectswithinthelifetimecontainer.Multiplelocatorscanpointtothesameobjectinstance.Forexample,anobjectcanhaveseparatelocatorsthatreferenceitthroughtheclasstype-name,theinterfacesitimplements,andtheobjectname.

Locatorscanberead-onlyorread-write,andtheBuildUpmethodofObjectBuildertakesaninstanceofanobjectthatimplementstheIReadWriteLocatorinterface.

UsingaPolicyList

APolicyListisasetofpolicies,eachrepresentedbyclassesthatimplementtheICreationPolicyinterface,thattogetherinfluencethewaythatanobjectiscreatedbyObjectBuilder.Policiescanbetransientorpermanent.

TransientpoliciesarethosegeneratedautomaticallybythestrategiesinObjectBuilderorthroughreflectionovertheattributesonthemethodsandpropertiesdeclaredintheclassfile.

PermanentpoliciesarethoseyoucreatebyimplementingtheICreationPolicyinterface.YoucanpassanarrayoftheseclassinstancestotheBuildUpmethodinObjectBuilder.

PipelineStages

ThepipelineinObjectBuilderconsistsoffourstages.Theseare:

PreCreation,whichoccursbeforeObjectBuildercreatesanewinstanceoftheobject.
Creation,whichoccursafterObjectBuildercreatesthenewobjectinstance
Initialization,whichoccursbeforepropertiesaresetonthenewobjectinstance
PostInitialization,whichoccursjustbeforereturnofthenewlycreatedobject

Table1showsthedefaultprocessesthatObjectBuildercarriesoutaseachstageofthepipeline:

Table1–ThestagesofstartingupaCompositeUIApplicationBlockapplication

Pipelinestage

ObjectBuilderStrategies

PreCreation

TypeMappingStrategy

SingletonStrategy

ConstructorReflectionStrategy

Creation

CreationStrategy

Initialization

PropertySetterStrategy

PropertyReflectionStrategy

MethodReflectionStrategy

MethodExecutionStrategy

PostInitialization

BuilderAwareStrategy

TheapplicationblocksthatuseObjectBuilderaddspecificstrategiestothepipeline,andyoucanaddyourownstrategiesifrequired.

StrategyTypes

ThedefaultstrategiesforObjectBuilderlistedinTable1are:

TypeMappingStrategy.Thisstrategycansettheactualreturntypeforobjects.Forexample,arequestforanabstractorinterfacetypeIMyObjectcanforceautomaticallytranslationintotheconcretetypeMyObject.
SingletonStrategy.ThisstrategyspecifieswhetherObjectBuilderreturnsanewinstanceofanobject,orreturnsanexistinginstanceifoneisavailable.
ConstructorReflectionStrategy.Thisstrategyinspectstheclasslookingforattributesdeclaredonconstructors,inparticularthe[Constructor]attribute,andchoosingwhichtousetoconstructtheobject.Moredetailsofhowparametersintheconstructordecoratedwiththe[Dependency]and[CreateNew]attributesinfluencebehavioroccurlaterinthissection.
CreationStrategy.Thisisthepointwherethenewobjectisinstantiated,usingeithertheconstructorortheActivatorclassmethods.
PropertySetterStrategy.Thisstrategycansetthevalueofpublicpropertiesofthenewobjectinstance,basedonpolicy.
PropertyReflectionStrategy.Thisstrategyinspectstheclasslookingforattributesonproperties,andappliesthesetothenewobjectinstance.Propertiesdecoratedwiththe[Dependency]and[CreateNew]attributescauseinjectionofthesevaluesintothenewobjectinstance.
MethodReflectionStrategy.ThisstrategyinspectstheclasslookingforattributesonmethodsthatmustrunduringtheInitializationstage.
MethodExecutionStrategy.Thisstrategyexecutesmethodsonthenewobjectinstance,dependingonpolicy.
BuilderAwareStrategy.ThisstrategyinspectstheclasstoseeifitimplementstheIBuilderAwareinterface.Ifitdoes,ObjectBuilderinformstheobjectwhenconstructioniscompleteandtheobjectisreadyforusebyrainingtheOnBuiltUpevent.IfObjectBuilderisexecutingtheTearDownmethod,itraisestheOnTearingDownevent.

YoucanderiveyourownclassfromtheBuilderBaseclassifyouwanttocreatemorestages,modifyorremovetheexistingones,useyourownstages,orpre-initializeabuildertosuityourrequirements.Lookingatthesourcefileforthebuilder(Builder.cs)providesanexampleofhowthisispossible.

Attribute-BasedDependencyInjection

ObjectBuildersupportsageneral-purposeattribute-baseddependencyinjection.Twoofthebuilt-instrategies,ConstructorInjectionStrategyandPropertyInjectionStrategy,providedependencyinjection.Bothofthesestrategiessupportacommonsetofattributesthatyoucanapplytovariables:

[CreateNew]tellsthedependencyinjectionsystemalwaystocreateanewoneofwhateveritisyouneed.ThisishelpfulforthingslikeMVCorMVP,wherecreatingaviewwillautomaticallygenerateanewcontroller/presenter.
[Dependency]isageneral-purposeattributewiththreeoptionalparameters:

Namespecifiesanamedobjectinsteadofanun-namedobject.Thedefaultifomittedisnull(un-named).

Theprovisionoftheseparametersonthe[Dependency]attributemeansthatitcansatisfyallofthefollowingrequirements:

IneedtheunnamedX(whereXisatype).Ifitdoesnotexist,throwanexception.
IneedtheunnamedX.Ifitdoesnotexist,createanewone.
IwanttheunnamedX.Ifitdoesnotexist,givemenullinstead.
IneedtheXnamedY(whereYisastring).Ifitdoesnotexist,throwanexception.
IneedtheXnamedY.Ifitdoesnotexist,createanewone.
IwanttheXnamedY.Ifitdoesnotexist,givemenullinstead.

Forexample,thiscodealwaysgeneratesanobjectoftypeMyCustomObject:

[C#]

CopyCode

usingMicrosoft.Practices.ObjectBuilder;
[Dependency(CreateType=typeof(MyCustomObject),
NotPresentBehavior=NotPresentBehavior.CreateNew)
publicICustomObjectMyCustomObject{set{...}}
IfthesystemcannotfindanICustomObject,itwillcreateanewMyCustomObject,andregisteritwiththetypeofICustomObjectforthenextpersonwhoneedsanICustomObject.Thedefaultisnull.

Constructor,Property,andMethodInjection

Threeofthebuilt-instrategies,theConstructorReflectionStrategy,PropertyReflectionStrategy,andMethodReflectionStrategy,usethe[Dependency]and[CreateNew]attributestocontroltheirbehavior.

TheConstructorReflectionStrategyhastwophases.First,itfiguresoutwhichconstructortouse.Second,itfiguresouthowtosatisfythoseconstructorparameters.

TheConstructorReflectionStrategyfirstlooksforanyconstructordecoratedwiththe[Constructor]attribute(therecanbeonlyoneofthese)andusesthisconstructoriffound.Ifthereisnodecoratedconstructor,yetthereisonlyoneconstructor,itwillusethatconstructor.Iftherearemultipleconstructorsbutnonecarriesthe[Constructor]attribute,thisstrategythrowsanexception.

Afterselectingtheconstructor,thestrategydetermineshowtofulfilltherequirementsoftheparameterstotheconstructor.Thesemaybemarkedwiththe[Dependency]and/or[CreateNew]attributes.Anyparameterwhichisundecoratedwillbetreatedasthoughithadbeendecoratedwiththedefault[Dependency]attribute(un-named,NotPresentBehavior=NotPresentBehavior.CreateNew,SearchMode=Up).

ThePropertyReflectionStrategylooksforpropertieswiththe[Dependency]and[CreateNew]attributes,andsatisfiesthemappropriately(theymustbepublicandhavesetters).Itdoesnotdoanythingwithanyundecoratedpropertiesonaclass.

TheMethodReflectionStrategylooksformethodsdecoratedwith[MethodInjection],whichexecuteduringtheinitializationphase.Theparametersofthesemethodsmaycontainthe[CreateNew]and[Dependency]attributes.Anyundecoratedparameteristreatedasthoughithadbeendecoratedwiththedefault[Dependency]attribute(un-named,NotPresentBehavior=NotPresentBehavior.CreateNew,SearchMode=Up).

HowtheCABusesObjectBuilder

TherearefivemorestrategiesinplacebydefaultintheCompositeUIApplicationBlock,asshownintheTable2.TheseareinadditiontothedefaultstrategiesimplementedwithinObjectBuilder.

Table2–ThestagesofstartingupaCompositeUIApplicationBlockapplication

Pipelinestage

CompositeUIApplicationBlockStrategies

PreCreation

TraceSourceStrategy

ConfigurationStrategy

StateStrategy

Initialization

EventBrokerStrategy

CommandStrategy

ThestrategieslistedinTable2are:

TraceSourceStrategy.ThisstrategyautomaticallyaddsaTraceSourceListenertothenewobjecttoprovidetracingcapabilities.
ConfigurationStrategy.Thisstrategyautomaticallyloadsanyconfigurationdataforthenewobject,basedonthepolicysettings.
StateStrategy.Thisstrategyautomaticallyloadsanystoredstateintothenewobject,basedonthepolicysettings.
EventBrokerStrategy.Thisstrategyautomaticallyregistersorun-registerseventinspectors.
CommandStrategy.Thisstrategyautomaticallyregistersorun-registerscommandhandlersforobjects.

CAB:http://practices.gotdotnet.com/projects/cab

Entlib:http://practices.gotdotnet.com/projects/entlib
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: