microsoft enterprise library 5 - documentation & helpacross different layers of their...
TRANSCRIPT
![Page 1: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1.jpg)
MicrosoftEnterpriseLibrary5.0
WelcometoEnterpriseLibrary
WelcometoEnterpriseLibrary.ThefollowingsectionsofthisguidancedescribethewaysthatyoucanuseEnterpriseLibraryandtheindividualapplicationblocksinyourapplications.Thesectionsare:
WhatIsEnterpriseLibrary?AboutThisReleaseofEnterpriseLibraryDevelopingApplicationswithEnterpriseLibraryDesignofEnterpriseLibraryTheCachingApplicationBlock
![Page 2: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/2.jpg)
TheCryptographyApplicationBlockTheDataAccessApplicationBlockTheExceptionHandlingApplicationBlockTheLoggingApplicationBlockThePolicyInjectionApplicationBlockTheSecurityApplicationBlockTheValidationApplicationBlockUnityDependencyInjectionandInterception
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 3: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/3.jpg)
MicrosoftEnterpriseLibrary5.0
WhatIsEnterpriseLibrary?
EnterpriseLibraryconsistsofacollectionofapplicationblocksandcoreinfrastructure.Allofthesearereusablesoftwarecomponentsdesignedtoassistdeveloperswithcommonenterprisedevelopmentchallenges.
EnterpriseLibraryalsoprovidesmanyhighlyconfigurablefeaturesthatmakeitmucheasiertomanagerepetitivetasks,knownascrosscuttingconcerns,whichoccurinmanyplacesinyourapplications.Theseincludetaskssuchaslogging,validation,caching,exceptionmanagement,andmore.Inaddition,thedependencyinjectioncontaineritprovidescanhelptosimplifyanddecoupleyourdesigns,makethemmoretestableandunderstandable,andhelpyoutoproducemoreefficientdesignsandimplementationsofallkindsofapplications.
![Page 4: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/4.jpg)
ThreeSimpleStepsforUsingEnterpriseLibrary
![Page 5: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/5.jpg)
BenefitsofEnterpriseLibrary
![Page 6: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/6.jpg)
GoalsforEnterpriseLibraryToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 7: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/7.jpg)
MicrosoftEnterpriseLibrary5.0
AboutThisReleaseofEnterpriseLibrary
ThissectioncontainsthefollowingtopicsthatwillhelpyoutounderstandthisreleaseofEnterpriseLibraryandhowyouuseitalongsideearlierversionsormigrateyourapplicationstothisversion.Thissectionincludesthefollowingtopics:
ChangesinThisReleaseTargetAudienceandSystemRequirementsContentsofEnterpriseLibraryMigrationandSide-by-SideExecutionRelatedpatterns&practicesLinksCopyrightandTermsofUse
![Page 8: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/8.jpg)
HowtoUseThisGuidanceToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 9: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/9.jpg)
MicrosoftEnterpriseLibrary5.0
ChangesinThisRelease
EnterpriseLibrary5.0isanewreleaseoftheMicrosoftpatterns&practicesEnterpriseLibrary.Oneofthemajorchangesistheimplementationoffulldependencyinjectioncapabilitiesforinstantiatingandmanagingthelifetimeofobjects,whichmakescreationofEnterpriseLibraryobjectsconsistentacrosstheentirelibrary.EnterpriseLibrarycannowbeusedwithdifferentdependencyinjectioncontainers.Unityisthedefaultdependencyinjectioncontainer.ForalternativeDIcontainerconfigurationplug-insgotothepatterns&practices:EnterpriseLibraryContribWebsite.
Thisreleasealsoincludesadditionsinfunctionalitytoseveraloftheexistingapplicationblocks.Inaddition,thisreleasehasbeenadaptedtoworkwithbothMicrosoftVisualStudio®2008andMicrosoftVisualStudio2010;andwiththeMicrosoft.NETFrameworkversions4.0and3.5withServicePack1.
Thefollowingsectionsdiscusstheseandotherchanges:IntegrationofUnityandObjectBuilderBreakingChangesChangesThatAffectAllApplicationBlocksChangestotheConfigurationToolChangestotheCachingApplicationBlockChangestotheCryptographyApplicationBlockChangestotheDataAccessApplicationBlockChangestotheExceptionHandlingApplicationBlockChangestotheLoggingApplicationBlockChangestothePolicyInjectionApplicationBlockChangestotheSecurityApplicationBlockChangestotheValidationApplicationBlock
GotoCodePlexforinformationonKnownIssues.
![Page 10: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/10.jpg)
IntegrationofUnityandObjectBuilder
![Page 12: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/12.jpg)
ChangesThatAffectAllApplicationBlocks
![Page 13: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/13.jpg)
ChangestotheConfigurationTools
![Page 14: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/14.jpg)
ChangestotheCachingApplicationBlock
![Page 15: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/15.jpg)
ChangestotheCryptographyApplicationBlock
![Page 16: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/16.jpg)
ChangestotheDataAccessApplicationBlock
![Page 17: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/17.jpg)
ChangestotheExceptionHandlingApplicationBlock
![Page 18: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/18.jpg)
ChangestotheLoggingApplicationBlock
![Page 19: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/19.jpg)
ChangestothePolicyInjectionApplicationBlock
![Page 20: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/20.jpg)
ChangestotheSecurityApplicationBlock
![Page 21: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/21.jpg)
ChangestotheValidationApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 22: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/22.jpg)
MicrosoftEnterpriseLibrary5.0
TargetAudienceandSystemRequirements
Thisguidanceisintendedforsoftwarearchitectsandsoftwaredevelopers.Togetthegreatestbenefitfromthisguidance,youshouldhaveanunderstandingofthefollowingtechnologies:
MicrosoftVisualC#®orMicrosoftVisualBasic®.NETMicrosoft.NETFramework
![Page 23: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/23.jpg)
SystemRequirementsandPrerequisitesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 24: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/24.jpg)
MicrosoftEnterpriseLibrary5.0
ContentsofEnterpriseLibrary
EnterpriseLibraryisacombinationofreusablecomponents,asupportinginfrastructure,andguidance.Itcontainsthefollowing:
Binaries.TheEnterpriseLibraryincludespre-compiled,strong-namedassembliesforallthesourcecode.Formoreinformation,seeDeployingEnterpriseLibrary.Sourcecode.TheEnterpriseLibraryincludesthesourcecodefortheapplicationblocks,thecoreinfrastructure,andtheconfigurationtool.Unittests.TheEnterpriseLibraryincludestheunitteststhatwerecreatedwhiletheapplicationblockswerebeingdeveloped.Formoreinformation,seeUnitTests.Documentation.EnterpriseLibraryincludesdocumentationthatcanbeviewedwiththeVisualStudioHelpsystem.ThedocumentationincludesguidanceabouthowtousetheEnterpriseLibraryandaclasslibraryreference.
AMigrationGuide,awiderangeofexamples,Hands-On-Labs,andotherlearningmaterialsareavailablefromtheEnterpriseLibrarycommunityWebsite.
ThefollowingtopicsdescribethecontentsofEnterpriseLibrarywithinthecontextoftheirfunction:
TheEnterpriseLibraryApplicationBlocksTheEnterpriseLibraryCoreTheEnterpriseLibraryConfigurationToolsTheInstanceCreationandDependencyInjectionMechanismUtilities,Tools,andGuidance
AdditionalfeaturesthatyoucanusewithEnterpriseLibraryareavailablefromtheEnterpriseLibraryCommunitySite.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 25: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/25.jpg)
MicrosoftEnterpriseLibrary5.0
TheEnterpriseLibraryApplicationBlocks
TheEnterpriseLibraryapplicationblockshelptoaddressthecommonproblemsthatdevelopersfacefromoneprojecttothenext.TheyaredesignedtoencapsulatetheMicrosoftrecommendedpracticesfor.NETapplications.Inaddition,theycanbeaddedto.NETapplicationsquicklyandeasily.Forexample,theDataAccessApplicationBlockprovidesaccesstothemostfrequentlyusedfeaturesofADO.NETinsimple-to-useclasses,thusboostingdeveloperproductivity.Italsoaddressesscenariosnotdirectlysupportedbytheunderlyingclasslibraries.
Differentapplicationshavedifferentrequirements,andyouwillnotfindthateveryapplicationblockisusefulineveryapplicationthatyoubuild.Beforeusinganapplicationblock,youshouldhaveagoodunderstandingofyourapplicationrequirementsandofthescenariosthattheapplicationblockisdesignedtoaddress.
ThisreleaseofEnterpriseLibrarycontainsthefollowingapplicationblocks:TheCachingApplicationBlock.Developerscanusethisapplicationblocktoincorporatealocalcacheintheirapplications.TheCryptographyApplicationBlock.Developerscanusethisapplicationblocktoincorporatehashingandsymmetricencryptionintheirapplications.TheDataAccessApplicationBlock.Developerscanusethisapplicationblocktoincorporatestandarddatabasefunctionalityintheirapplications.TheExceptionHandlingApplicationBlock.Developersandpolicymakerscanusethisapplicationblocktocreateaconsistentstrategyforprocessingexceptionsthatoccurthroughoutthearchitecturallayersofenterpriseapplications.TheLoggingApplicationBlock.Developerscanusethisapplicationblocktoincludestandardloggingfunctionalityintheirapplicationsandsystemsadministratorscanusetheconfigurationtooltoadjustthegranularityofloggingatruntime.ThePolicyInjectionApplicationBlock.Thisblockcontainslegacycodeforbackwardscompatibilitywithexistingapplications.ThenewfunctionalityisavailablebyusingtheUnityinterceptionmechanismand
![Page 26: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/26.jpg)
callhandlerslocatedintherelatedapplicationblockassemblies.TheSecurityApplicationBlock.Developerscanusethisapplicationblocktoincorporateauthorizationandsecuritycachingfunctionalityintheirapplications.TheValidationApplicationBlock.Developerscanusethisapplicationblocktocreatevalidationrulesforbusinessobjectsthatcanbeusedacrossdifferentlayersoftheirapplications.UnityDependencyInjectionandInterception.Developerscanusethistoimplementalightweight,extensibledependencyinjectioncontainerwithsupportforconstructor,property,andmethodcallinjection;andtocapturecallstotargetobjectsandaddadditionalfunctionalitytotheobject.
TheEnterpriseLibraryalsoincludesasetofcorefunctions,includingconfigurationandinstrumentation.Allotherapplicationblocksusethesefunctions.SeeTheEnterpriseLibraryCore.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 27: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/27.jpg)
MicrosoftEnterpriseLibrary5.0
TheEnterpriseLibraryCore
EnterpriseLibrarycontainsasetofcorefeaturesthatintegratetheapplicationblockswiththeconfigurationsystem,supportalternativeconfigurationsystems,andprovidecommonutilitiesusedacrossalloftheapplicationblocks.ThefollowingaresomeexamplesofthecontentsoftheEnterpriseLibrarycore:
Run-timeconfigurationclassesandprovidersthatexposeconfigurationdatatothelibrary,theapplicationblocks,andusers'applicationsatruntimeCommonutilityfunctionsfortaskssuchasserialization,usedinmanyplacesthroughoutthelibraryandtheapplicationblocksandavailablefordeveloperstouseintheircodeInstrumentationfeaturesthatallowdevelopersandadministratorstomonitorthebehaviorandperformanceoftheapplicationblocksatruntimeDesign-timeconfigurationclassesthatsupporttheconfigurationtoolsandallowdeveloperstospecifyandpersistconfigurationinformationforthelibraryandtheapplicationblocks
FormoredetailsaboutthedesignoftheEnterpriseLibrarycorefeatures,seeTheEnterpriseLibraryCoreintheDesignofEnterpriseLibrarysectionofthisguidance.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 28: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/28.jpg)
MicrosoftEnterpriseLibrary5.0
TheEnterpriseLibraryConfigurationTools
Applicationblocksaredesignedtobeusedinavarietyofenterpriseapplicationdevelopmentscenarios.Thisdesignapproachenablesyoutoeasilyadaptanapplicationblocktomeettheneedsofyoursituation.Youdothiswithconfigurationsettings,whichyoucaneasilychangeusingtheconfigurationtools.Youcandefineconfigurationsettingsforanapplicationblock'scentralfunctionalityandforeachprovidertype.
YoucanuseVisualStudiotocreateandmodifyconfigurationfilesoryoucanusethestand-aloneEnterpriseLibraryconfigurationconsole.Collectively,theVisualStudiointegratedconfigurationeditorandthestand-aloneconfigurationconsolearereferredtoastheconfigurationtools.Bothoftheseconfigurationtoolshaveidenticalfunctionality.Withthesetools,youcanchangeandvalidateapplicationblocksettingswithoutmanuallyeditingtheXMLconfigurationfileswheretheyarestored.Theconfigurationtoolsdisplaythesesettingsandsupplydefaultvaluesthatyoucanchange.
Eachapplicationblockdefinespointsofextensibility,wheredeveloperscanincludetheirownimplementations(typically,theseareproviders)withspecificfunctionality.Forexample,youcanaddyourowncustomlogentryformatterstotheLoggingApplicationBlock.Thesecustomproviderscanbeinterchangedwiththeprovidersthataresuppliedwiththeapplicationblock.TheconfigurationconsoleletsyouselectthecustombackingstoreandwritesthisinformationtotheappropriateXMLconfigurationfile.Thismeansthattheapplicationwillusethecustomstorewithoutanycodechangesandwithoutbeingrecompiled.
TheVisualStudiointegratedconfigurationtoolisnamedtheconfigurationeditor.Theconfigurationeditorhasthesamefunctionalityasthestand-aloneconfigurationconsole,butitusestheVisualStudioPropertiesgridtodisplayanapplicationblock'spropertiesandusestheerrorslisttodisplayconfigurationerrors.
Thefollowingdescribessomeoftheactivitiestheconfigurationtoolshelpyouwith:
Youcanusetheconfigurationtoolstocreateandmodifystandard.NET
![Page 29: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/29.jpg)
Framework<appSettings>sections.Formoreinformation,seeUsingtheappSettingsSection.Youcanusetheconfigurationtoolstotailoranapplicationblock'sconfigurationtoaparticularrun-timeenvironment.Formoreinformation,seeConfiguringaDeploymentEnvironment.Youcanusetheconfigurationtoolstoencryptanddecryptthedatacontainedinconfigurationsections.Formoreinformation,seeEncryptingConfigurationData.
Usingconfigurationsettingstoadaptanapplicationblocktoaparticularsituationhastwoadvantages:
Differentpeoplecanconfigurethecharacteristicsofanapplicationblockatdifferenttimesduringtheapplicationlifecycle.Forexample,adevelopercouldconfigureaprovidertoaccessaparticulardatabaseduringapplicationdevelopment,whileasystemadministratorcoulddecideduringdeploymenttoencryptthedatabaseconnectionstrings.Youcanchangetheapplicationblockconfigurationincrementallyforincreasinglycomplexsituations.Forexample,youcouldinitiallyconfigureanapplicationblocktousethedefaultsettingsandproviders.Asyourunderstandingofthescenariodeepens,youcanchangetheapplicationblockconfigurationwithoutmodifyingitscode,recompilingit,orredeployingit.
FormoreinformationonusingtheVisualStudioconfigurationeditorandtheconfigurationconsoleseeUsingtheConfigurationTools.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 30: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/30.jpg)
MicrosoftEnterpriseLibrary5.0
TheInstanceCreationandDependencyInjectionMechanism
EnterpriseLibraryincorporatesaneasy-to-usemechanismforcreatingandwiringinstancesofobjects(whichmaycontainotherdependentobjects),andmanagingtheirlifetimes.ThisfeatureistheUnitycontainerandthefollowingdesignpatternsareused:
DependencyInjectionInversionofControl(IoC)ServiceLocatorServiceContainerFactoryBuilder
![Page 31: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/31.jpg)
UnityandEnterpriseLibraryToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 32: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/32.jpg)
MicrosoftEnterpriseLibrary5.0
Utilities,Tools,andGuidance
TohelpdeveloperslearnhowtouseEnterpriseLibrary,andtomakesuretheygetoptimumresultsfromit,theinstallationofEnterpriseLibraryincludesthefollowingutilities,tools,andguidance:
BatchfilesthatbuildtheEnterpriseLibrarysourcecodeandcopytheassembliestotheappropriatelocations.Formoreinformation,seeBuildingEnterpriseLibraryfromtheSourceCode.UtilitiestoinstalltheinstrumentationrequiredbyEnterpriseLibrary.Formoreinformation,seeEnablingInstrumentation.
Inaddition,thesourcecodeforEnterpriseLibraryincludesVisualStudioprojectsandunitteststhatdeveloperscanusetoextendandmodifythelibraryandtheapplicationblocks.Developerscanmakesureapplicationsstillmeetthedesignrequirementsbyrunningtheunittestsandwritingnewtests.ForinformationabouttheunittestsincludedwithEnterpriseLibrary,seeUnitTests.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 33: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/33.jpg)
MicrosoftEnterpriseLibrary5.0
MigrationandSide-by-SideExecution
Ingeneral,applicationsbuiltforEnterpriseLibraryfor.NETFramework2.0inJanuary2006andlaterwillfunctionwiththisreleaseofEnterpriseLibrarywithouttheneedforanycodechanges.Itwillbenecessarytoupdatethereferencestorefertothenewassembliesandtoupdatetheconfigurationfilestoreferencethecorrectversionoftheassemblies.ToreviewthefewbreakingchangesyoumayneedtoaddressgototheBreakingChangessection.
ThisversionofEnterpriseLibrarycanalsobeinstalledsidebysidewithearlierversionsofEnterpriseLibrary.YoucandeploynewapplicationswrittenforthisversionofEnterpriseLibraryalongwithapplicationswrittenforearlierversions.Inaddition,youcanchoosetomigrateexistingapplications,oneassemblyatatime,tothenewversion.
Ifyoudecidetouseside-by-sideexecution,youmustdeploythedifferentEnterpriseLibraryversionsindifferentdirectories.Inanyspecificdirectory,youcannotmixandmatchassembliesfromdifferentversions.Forexample,youcannothaveDataAccessApplicationBlockversion5.0inthesamedirectorywithCachingApplicationBlockversion4.0.
TheshippedprojectfilesusedataintheAssemblyInfo.csfiletobuildassembliesthathavedifferentversioninformation.Thisenablesyoutousestrongnamesandtoadddifferentversionstotheglobalassemblycacheforside-by-sideexecution.
![Page 34: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/34.jpg)
PartialMigrationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 35: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/35.jpg)
MicrosoftEnterpriseLibrary5.0
Relatedpatterns&practicesLinks
ForinformationrelatedtoEnterpriseLibrary,andothertoolsandguidancefordesigningandbuildingapplications,seethepatterns&practicesWebsiteandguides:
Microsoftpatterns&practicesDeveloperCenterDeveloper'sGuidetoMicrosoftEnterpriseLibrary5MicrosoftApplicationArchitectureGuide,2ndEditionSolutionDevelopmentFundamentalspatterns&practicesSecurityGuidanceforApplicationsIndex.NETDataAccessArchitectureGuideImproving.NETApplicationPerformanceandScalabilityMonitoringin.NETDistributedApplicationDesignDeploying.NETFramework-basedApplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 36: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/36.jpg)
MicrosoftEnterpriseLibrary5.0
CopyrightandTermsofUse
Thisdocumentisprovided"as-is".Informationandviewsexpressedinthisdocument,includingURLandotherInternetWebsitereferences,maychangewithoutnotice.Youbeartheriskofusingit.
Someexamplesdepictedhereinareprovidedforillustrationonlyandarefictitious.Norealassociationorconnectionisintendedorshouldbeinferred.
ThisdocumentdoesnotprovideyouwithanylegalrightstoanyintellectualpropertyinanyMicrosoftproduct.Youmaycopyandusethisdocumentforyourinternal,referencepurposes.
©2010Microsoft.Allrightsreserved.
Microsoft,Windows,WindowsServer,WindowsVista,VisualC#,VisualBasic,andVisualStudioaretrademarksoftheMicrosoftgroupofcompanies.Allothertrademarksarepropertyoftheirrespectiveowners.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 37: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/37.jpg)
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationswithEnterpriseLibrary
EnterpriseLibrarycanbeusefulinavarietyofsituations;thefollowingaresomeexamples:
EnterpriseLibraryprovidessufficientfunctionalitytosupportmanycommonscenariosthatenterprise-levelapplicationsmustaddress.EnterpriseLibrarycanserveasthebasisforacustomlibrary.Youcantakeadvantageoftheextensibilitypointsincorporatedineachapplicationblockandextendtheapplicationblockbysupplyingnewproviders.Youcanalsomodifythesourcecodefortheexistingapplicationblockstoincorporatenewfunctionality.Youcandevelopextensionsforexistingapplicationblocksandnewapplicationblocksyourself,oryoucanuseextensionsandapplicationblocksdevelopedbyothers.Finally,youcanaddnewapplicationblockstoEnterpriseLibrary.EnterpriseLibraryisdesignedsothatitsapplicationblockscanfunctionindependentlyofeachother.Youhavetoaddonlytheapplicationblocksthatyourapplicationwilluse;youdonothavetoaddtheentirelibrary.EnterpriseLibraryincludesthesourcecodefortheapplicationblocks.ThismeansyoucanmodifytheapplicationblockstomergeintoyourexistinglibraryoryoucanusepartsoftheEnterpriseLibrarysourcecodeinotherapplicationblocksorapplicationsthatyoubuild.EnterpriseLibraryincludescomprehensivedocumentation.Thismeansthatyoucanusethelibraryandthesourcecodeastoolsforlearningarchitectural,design,andcodingbestpractices.Awiderangeofexamples,Hands-On-Labs,andotherlearningmaterialsareavailablefromtheEnterpriseLibrarycommunityWebsite.
ThissectiondescribesthegeneralproceduresforworkingwithEnterpriseLibraryinyourapplications.Youcanfinddetailsofhowtouseeachoftheapplicationblocksintherelevantsectionforeach.Thissectionincludesthefollowingsetsofrelatedtopics:
ConfiguringEnterpriseLibrary.ThesetopicsdescribethebasicandmoreadvancedproceduresforconfiguringEnterpriseLibrary;includingusingtheconfigurationtools,sharingandmanagingconfigurationformultipleapplications,configuringEnterpriseLibraryprogrammatically,
![Page 38: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/38.jpg)
encryptingconfigurationfiles,andenablingthebuilt-ininstrumentation.UsingEnterpriseLibraryinApplications.ThesetopicsdescribehowtoaddtheEnterpriseLibraryassembliestoyourprojects,importtherequirednamespaces,andcreateinstancesofEnterpriseLibraryobjectsthatexercisethefunctionalityoftheapplicationblocks.DeployingEnterpriseLibrary.ThesetopicsdiscusstheissuesthatyoushouldconsiderwhendeployingEnterpriseLibraryandapplicationsthatuseit.ThisincludesversioningandstrongnamingassembliesifyoumodifythesourcecodeforEnterpriseLibrary,andpointerstohelpyouuseEnterpriseLibraryinpartialtrustscenarios.AdministeringEnterpriseLibrary.ThistopicsummarizesthetechniquesavailabletoadministratorsandoperatorsforrunningmultipleversionsofEnterpriseLibrary,managingconfiguration,usingthebuilt-ininstrumentation,andintegratingwithsystemmanagementtools.ExtendingandModifyingEnterpriseLibrary.ThesetopicsprovideadviceonextendingandmodifyingEnterpriseLibrarybychangingthesourcecode,andinformationaboutcreatingcustomprovidersthatintegratewithEnterpriseLibraryandtheconfigurationtools.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 39: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/39.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringEnterpriseLibrary
ConfigurationinformationfortheEnterpriseLibraryapplicationblocksisstoredinXMLformat.Typically,theinformationexistsinanXMLfile.Bydefault,theXMLfilethatcontainstheinformationistheapplicationconfigurationfile.
YoucanmanuallyedittheXMLdata,buttheEnterpriseLibraryprovidestwoconfigurationtoolsthatgreatlysimplifythistask.Thesetoolsarethestand-aloneconfigurationconsoleandtheconfigurationeditorthatisintegratedwithVisualStudio®.IfyouchoosetomanuallyedittheXML,refertotheappropriateapplicationblockdocumentationforschemadetails.
Note:Whencreatingaconfigurationfileandaddingapplicationblocks,UsingtheConfigurationToolsprovidesalesserrorproneexperienceandistherecommendedprocess.EditingtheXMLinVisualStudiodoesnotenforcetheconfigurationfilehierarchyatalllevelsandcanresultininvalidXML.
Theconfigurationfilesarenotencrypted,theyareincleartext,bydefault.Aconfigurationfilemaycontainsensitiveinformationaboutconnectionstrings,userIDs,passwords,databaseservers,andcatalogs.Youshouldprotectthisinformationagainstunauthorizedread/writeoperationsbyusingencryptiontechniques.Toprovidesecuritytheymustbeencryptedorprotectedusingaccesscontrollists(ACLs).Itisrecommendedthattheconfigurationstorebeinthesametrustboundaryandthatdecryptingtheconfigurationisdoneinthesametrustboundaryaftertheconfigurationisread.Forinformationabouthowtoencryptconfigurationfiles,seeEncryptingConfigurationData.
Thissectionincludesthefollowingtopics:UsingtheConfigurationToolsAdvancedConfigurationScenariosUsingGroupPolicywithEnterpriseLibraryConfiguringaDeploymentEnvironmentUsingtheFluentConfigurationAPIUsingtheappSettingsSection
![Page 40: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/40.jpg)
UpdatingConfigurationSettingsatRunTimeEncryptingConfigurationDataEnablingInstrumentationSourceSchemaforEnterpriseLibraryCore
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 41: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/41.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheConfigurationTools
TheEnterpriseLibraryconfigurationtoolsaregraphicaltoolsthatallowyoutocreate,change,andvalidateapplicationblocksettingswithouthavingtomanuallyedittheXMLconfigurationfileswheretheyarestored.ThereisaconfigurationeditorthatintegrateswithVisualStudio2008,plusstandaloneversionsfordifferentoperatingsystemandMicrosoft®.NETFrameworkversionsthatyoucanlaunchfromwithinVisualStudiooropenfromyourStartmenu.
Thesetoolsdisplaytheavailableconfigurationsettings,thedefaultvaluesthatyoucanchange,andinformationaboutwhateachsettingmeans.
Thistopiccontainsthefollowingsections:LaunchingConfigurationEditorfromVisualStudioSettingtheVisualStudioConfigurationEditorastheDefaultEditorLaunchingtheStandaloneConfigurationToolUsingWizardsintheConfigurationToolUsingtheKeyboardwiththeConfigurationToolTheConfigurationTypeSelectorEnterpriseLibraryConfigurationSchemaBuildingtheConfigurationConsoleSpecifyingDifferentAssembliesConfigurationToolUsageNotes
![Page 42: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/42.jpg)
LaunchingtheConfigurationEditorfromVisualStudio
![Page 43: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/43.jpg)
SettingtheVisualStudioConfigurationEditorastheDefaultEditor
![Page 44: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/44.jpg)
LaunchingtheStand-aloneConfigurationTool
![Page 45: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/45.jpg)
UsingWizardsintheConfigurationTool
![Page 46: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/46.jpg)
UsingtheKeyboardwiththeConfigurationTool
![Page 47: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/47.jpg)
TheConfigurationTypeSelector
![Page 48: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/48.jpg)
EnterpriseLibraryConfigurationSchema
![Page 49: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/49.jpg)
BuildingtheConfigurationConsole
![Page 50: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/50.jpg)
SpecifyingDifferentAssemblies
![Page 51: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/51.jpg)
ConfigurationToolUsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 52: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/52.jpg)
MicrosoftEnterpriseLibrary5.0
AdvancedConfigurationScenarios
TheEnterpriseLibrarystandaloneconfigurationconsoleandtheVisualStudiointegratedconfigurationeditorallowyoutosatisfyarangeofadvancedconfigurationscenariosbasedonexternalconfigurationsourcessuchasdiskfiles.Forexample,youcan:
Readconfigurationinformationfromawiderangeofsources.Enforcecommonconfigurationsettingsacrossmultipleapplications.Shareconfigurationsettingsbetweenapplications.Specifyacoresetofconfigurationsettingsthatapplicationscaninherit.Mergeconfigurationsettingsthatarestoredinasharedlocation.Createdifferentconfigurationsfordifferentdeploymentenvironments.
ThedefaultandsimplestscenarioforconfiguringEnterpriseLibraryistoconfigureyourapplicationusingtheconfigurationtoolwithoutaddingaConfigurationSourcessectionoranyconfigurationsources.ThisistheapproachdescribedinUsingtheConfigurationTools.
Whenyouusetheconfigurationtoolswithoutspecifyingaconfigurationsource,theydefaulttousingtheSystemConfigurationSourcetocreateasingleconfigurationfilethatcontainstheentireconfigurationfortheapplication.YourapplicationwillexpectthistobenamedApp.configfile(whichiscopiedto[exe-name].configwhenyoucompileyourapplication)orWeb.config(dependingonthetechnologyyouareusing),andwillreaditautomatically.
YoucanselectAddConfigurationSettingsontheBlocksmenutodisplaythesectionthatcontainsthedefaultSystemConfigurationSource.IfyouclickthechevronarrowtotherightoftheConfigurationSourcestitletoopenthesectionpropertiespaneyoucanseethattheSystemConfigurationSourceisalso,bydefault,specifiedastheSelectedSource—theconfigurationsourcetowhichtheconfigurationgeneratedbythetoolwillbewritten.WhenanapplicationthatusesEnterpriseLibraryreadstheconfiguration,itusesthesettingsspecifiedfortheselectedsource.
Byaddingadditionalconfigurationsources,youcanimplementmoreadvancedconfigurationscenarios.Thefollowingsectionsdescribethescenariosthatyoucanimplementusingtheconfigurationtools:
![Page 53: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/53.jpg)
UsingaNon-defaultConfigurationStoreSharingtheSameConfigurationbetweenMultipleApplicationsManagingandEnforcingConfigurationforMultipleApplicationsSharingConfigurationSectionsacrossMultipleApplicationsApplyingaCommonConfigurationStructureforApplicationsManagingConfigurationinDifferentDeploymentEnvironments
Youcanalsochangethecontentsofaconfigurationfileprogrammatically,whichisusefulwhenworkingwithsharedconfigurationstoredasdiskfiles.Formoreinformation,seeUpdatingSharedConfigurationSettingsProgrammatically.Forlinkstorelatedtopicsandmoredetailsofhowtheconfigurationsystemworks,seeMoreInformationattheendofthistopic.
![Page 55: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/55.jpg)
SharingtheSameConfigurationbetweenMultipleApplications
![Page 56: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/56.jpg)
ManagingandEnforcingConfigurationforMultipleApplications
![Page 57: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/57.jpg)
SharingConfigurationSectionsacrossMultipleApplications
![Page 58: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/58.jpg)
ApplyingaCommonConfigurationStructureforApplications
![Page 59: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/59.jpg)
ManagingConfigurationinDifferentDeploymentEnvironments
![Page 60: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/60.jpg)
UpdatingSharedConfigurationSettingsProgrammatically
![Page 61: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/61.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 62: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/62.jpg)
MicrosoftEnterpriseLibrary5.0
UsingaNon-defaultConfigurationStore
TheEnterpriseLibraryconfigurationtoolsallowyoutospecifytheconfigurationsourcetobereadatruntimetoconfigureyourapplication.Youcanpointtoconfigurationfilesorothertypesofconfigurationsourcesfromwhichtoreadconfigurationinformation.Thistopicexplainshowtoaddanon-defaultconfigurationsourcetoyourconfiguration.ItusestheFile-basedConfigurationSource,butthesameapproachisusedwithotherconfigurationsources.
Toaddaconfigurationsource1. Onthetaskbar,clickStart,pointtoAllPrograms,pointtoMicrosoft
patterns&practices,pointtoEnterpriseLibrary5.0,pointtoEnterpriseLibraryConfiguration,andthenselecttheversionoftheconfigurationeditoryourequire.Alternatively,right-clickonaconfigurationfileinVisualStudioSolutionExplorerandclickEditEnterpriseLibraryV5Configuration.
2. SelectAddConfigurationSettingsontheBlocksmenutodisplaythesectionthatcontainstheconfigurationsources.
3. ClicktheSourcesplus-signicon,pointtoAddSources,andthenclickAddFile-basedConfigurationSource.
4. AnewsectionisaddedtotheSourcespanewiththedefaultnameofthetypeofconfigurationsourceyouadded,forexampleFile-basedConfigurationSource.Ifyouaddmorethanoneofthesameconfigurationsourcetype,thedefaultnamesincrementbyoneeachtime.
5. Setthepropertiesoftheconfigurationsource.Forexample,settheFilePathpropertybytypingthefilepathandnameofthefile,orby
![Page 63: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/63.jpg)
clickingtheellipsisbutton(…)andnavigatingtothefileyouwanttouse.Thefilecanbelocatedonthelocalmachine,orinasharedlocationifyouwanttousethesameconfigurationformultipleapplicationsorapplicationlayers.
6. EdittheNamepropertyoftheconfigurationsourceifrequired.7. ClicktheConfigurationSourcespropertyexpanderchevrontoopen
thepropertiespaneforthesection.SettheSelectedSourcepropertybyselectingtheconfigurationsourceyouwanttouseforyourapplicationfromthedrop-downlist.
8. OntheFile,menuclickSaveorSaveAs.
![Page 64: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/64.jpg)
Note:AQuickStartsamplenamedSqlConfigurationthatimplementsanexampleSQLConfigurationSourcetodemonstratehowyoucanstoreconfigurationinformationinadatabaseisavailablefromtheEnterpriseLibraryContribWebsite.ThisproviderusestheDataAccessApplicationBlocktoreadconfigurationsettingsfromaSQLServer©database.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 65: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/65.jpg)
MicrosoftEnterpriseLibrary5.0
SharingConfigurationSectionsacrossMultipleApplications
Youcanuseredirectiontoreadtheconfigurationforindividualapplicationblocks(individualconfigurationsections)fromasharedlocationorotherconfigurationsource.Thisenablesyoutousealocalapplicationconfigurationforsomeapplicationblocks,whilereadingandincludingthesharedsectionsconfiguration.Youcreatecompositeconfigurationslikethisbyspecifyingadditionalsourcesinyourapplicationconfigurationfile.Thecontentsoftheindividualsectionsintheconfigurationsourcecanbereadandincludedwiththecontentsofyourdefaultapplicationconfigurationfileatruntime.
ThefollowingprocedureexplainshowyoucanusetheconfigurationtoolstoredirectEnterpriseLibrarytoreadaspecificconfigurationsection'scontentfromaspecifiedsource.
Touseredirectiontoreadaconfigurationsectionfromasharedsource1. Onthetaskbar,clickStart,pointtoAllPrograms,pointtoMicrosoft
patterns&practices,pointtoEnterpriseLibrary5.0,pointtoEnterpriseLibraryConfiguration,andthenselecttheversionoftheconfigurationeditoryourequire.Alternatively,right-clickonaconfigurationfileinVisualStudioSolutionExplorerandclickEditEnterpriseLibraryV5Configuration.
2. OntheBlocksmenuclickAddConfigurationSettings.3. IntheSourcespaneclicktheplus-signicon,pointtoAddSourcesand
thenclickthetypeofconfigurationsourceyouwanttoaddtotheconfiguration.Thisistheconfigurationsourcetowhichyouwillredirectconfigurationsections.Inthisexample,weaddaFile-basedConfigurationSource.
4. IntheSourcescolumn,enterthedesiredFilePathpropertyforthenew
![Page 66: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/66.jpg)
configurationsourcebytypingthepathandfilenameorbyclickingtheellipses(...)buttonandnavigatingtothefile.
5. YoucannowredirectsectionsfromyourlocalsourcetoanotherusingtheRedirectedSectionspane.ClicktheplussigniconintheRedirectedSectionscolumnandclickAddRedirectedSection.
6. InthenewRedirectedSectionthatisdisplayed,selecttheconfigurationsectionthatyouwanttoredirecttoasharedconfigurationsource.Afteryouselectthesection,thenameoftheredirectedsectionchangestoreflectthis.
7. Selecttheconfigurationsourcethatwillexposethesharedconfigurationsectionyouwanttouseinthedrop-downlistfortheConfigurationSourcepropertyoftheredirectedsection.Aconnectinglineappearsshowingwhichconfigurationsourcewillprovidetheinformationfortheredirectedsection.
![Page 67: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/67.jpg)
8. ClickSaveorSaveAstosavetheconfiguration.
Note:IntheConfigurationTool,whenredirectedsectionsareusedwithaSelectedSourceotherthanSystemConfigurationSource,theredirectedsectionsconfigurationinformationwillstillbesavedtotheSystemConfigurationSource,whichisthefileopenedintheconfigurationtool.Toeditthecontentsofthesharedconfigurationsections,opentheconfigurationthatcontainsthemdirectly.
![Page 68: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/68.jpg)
AnExampleoftheXMLGeneratedbyRedirectedSectionsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 69: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/69.jpg)
MicrosoftEnterpriseLibrary5.0
ApplyingaCommonConfigurationStructureforApplications
Ifyouaddaconfigurationsourcetoyourapplicationconfigurationandspecifythatthisconfigurationsourceistheparentsource,EnterpriseLibrarywillreadthecontentsofthisconfigurationsourceandmergeanylocalconfigurationsettingsyouhavespecifiedwiththisparentconfiguration.Effectively,itinheritsthesharedconfigurationandthenappliesthelocalsettingstooverrideanythatoccurinbothconfigurations.Youcanusetheconfigurationtooltospecifyaparentconfigurationthatwillbeinherited.
Toinheritasharedconfigurationstructureandsettingsfromanotherconfigurationsource
1. Onthetaskbar,clickStart,pointtoAllPrograms,pointtoMicrosoftpatterns&practices,pointtoEnterpriseLibrary5.0,pointtoEnterpriseLibraryConfiguration,andthenselecttheversionoftheconfigurationeditoryourequire.Alternatively,right-clickonaconfigurationfileinVisualStudioSolutionExplorerandclickEditEnterpriseLibraryV5Configuration.
2. OntheBlocksmenuclickAddConfigurationSettings.3. IntheSourcespaneclicktheplus-signicon,pointtoAddSourcesand
thenclickthetypeofconfigurationsourceyouwanttoaddtotheconfiguration.Thisistheconfigurationsourcefromwhichyouwillinheritconfigurationinformation.Inthisexample,weaddaFile-basedConfigurationSource.
4. Setthepropertiesoftheconfigurationsourceyouadded.Forexample,enterthedesiredFilePathpropertyforthenewconfigurationsourcebytypingthepathandfilenameorbyclickingtheellipses(...)buttonandnavigatingtothefile.
![Page 70: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/70.jpg)
5. ClicktheConfigurationSourcespropertyexpanderchevrontoopenthepropertiespaneforthesection.SettheParentSourcepropertytotheconfigurationsourcewhosesettingsyouwanttoinherit.
6. ClickSaveorSaveAsontheFilemenutosaveyourconfiguration.
Settingsintheinheritedconfigurationsourcewillapplytoyourapplicationunlessyouoverridethembyconfiguringthesamesettinginyourlocalconfiguration.Forinformationabouthowsettingsareinheritedandmerged,seeMergeRulesforInheritedConfiguration.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,pleasesendemailto
![Page 71: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/71.jpg)
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 72: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/72.jpg)
MicrosoftEnterpriseLibrary5.0
MergeRulesforInheritedConfiguration
Whenyouspecifyaparentsourcefromwhichyouinheritsharedconfigurationinformation,allofthatconfigurationinformationisreadandthesettingsaremergedatrun-timeatthelevelofindividualsettingelements.Forexample,youcanaddexceptionhandlerstoanexistingpolicy,oraddapropertytoanelementinthelocalconfigurationthatdoesnotexistinthedefaultsettings.TheruntimemergebasicallybehaveslikealogicalOR.Iftheelementorpropertyisinoneoftheconfigurationfiles,itwillbepresentinthemergedconfiguration.
Ifanelementorpropertyispresentinbothsourceswhenyouinheritasection,theelementinthelocalconfiguration(thelocalsource)istheonepresentintheresultingmergedconfiguration.Inheritancecanonlybeoneleveldeep;youcannotdefineaparentsourceforaconfigurationsourcethatisitselfusedasaparentsource.Thispreventstheaccidentalcreationofcircularreferencesandendlessrecursion.
Note:Whenyouuseenvironmentaloverridestospecifydifferentconfigurationsfordifferentdeploymentenvironmentsinconjunctionwithsettingsinheritedfromaparentsource,themergerulesdescribedheredonotapplytotheinheritedconfigurationsettings.Themergedconfigurationisspecifiedbythecombinationofthecommonandthedelta(differences)configurationfilesthatyoumerge.
Whenyouuseredirectedsections,andanelementorpropertyispresentinbothsources,theelementfromthesharedconfiguration(thesourceyouredirectthesectionto)istheonepresentintheresultingmergedconfiguration.Localsettingsinaredirectedsectionareignored.Ifyouspecifyaparentsourceaswellasredirectedsections,themergebehaviorappliestotheredirectedsections.
Toavoidissueswhenyouusedifferenttoolstomanageyourconfiguration,youshouldavoidinheritingthestandard.NETconfigurationsectionsthatarealsousedbyEnterpriseLibrary,suchasappSettingsandconnectionStrings.
![Page 73: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/73.jpg)
Whencreatingacompositeconfiguration,thereisahierarchytothecomponentsmergedintoyourEnterpriseLibraryconfigurationatruntime,asdescribedinAdditiveMergebelow.Inaddition,thereisahierarchyformergingofthecollectionsfromthespecifiedsources,describedinthesectionMergedCollectionsOrderlaterinthistopic.
![Page 74: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/74.jpg)
AdditiveMerge
![Page 75: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/75.jpg)
MergedCollectionsOrderToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 76: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/76.jpg)
MicrosoftEnterpriseLibrary5.0
AbouttheConfigurationSystem
EnterpriseLibraryfirstlooksatthedefaultconfigurationfile(thecurrentapplicationdomainconfigurationfile).ThiswillbeeitheryourApp.configfile(whichiscopiedto[exe-name].configwhenyoucompileyourapplication)oryourWeb.configfile.Thisfilemaycontainaconfigurationsectionthatdefinesadditionalconfigurationsources.Thecoreconfigurationclassesthatsupportreadingconfigurationinformationfirsttrytoreadtherequestedconfigurationsectionfromtheconfiguredsourcelocation.
TheenterpriseLibrary.ConfigurationSourcesectionintheconfigurationfilecarriestheselectedSourceattribute,whichspecifiestheconfigurationsourcethattheapplicationshoulduse.The<enterpriseLibrary.ConfigurationSource>sectionisretrievedfromthecurrentapplicationdomain'sconfigurationfile,andEnterpriseLibraryusestheconfigurationinformationexposedbytheconfigurationsourcespecifiedbytheselectedSourceattribute.
ThesourcedefinedbytheselectedSourceattributecouldbeanyofthefollowingsources:
ASystemConfigurationSource,whichreadsfromtheapplication'sconfigurationfile.
![Page 77: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/77.jpg)
AFile-basedConfigurationSource,whichreadsfromanarbitraryfile.AManageableConfigurationSource,whichreadsfromanarbitraryfileandappliesgrouppolicyoverrides,oranycustomconfigurationsource.ThesampleSQLConfigurationSourceavailablefromtheEnterpriseLibraryContribProjectWebsite,whichreadsconfigurationdatafromadatabase.AcustomconfigurationsourcethatyoucreateandaddtoEnterpriseLibrary.
Ifthereisno<enterpriseLibrary.ConfigurationSource>sectionintheconfigurationfile,aninstanceoftheSystemConfigurationSourceclassisusedbydefaultandbecomestheapplicationconfigurationsource.
Note:ConfigurationsourcesareanextensibilitypointinEnterpriseLibrary.
ThefollowingXMLfragmentshowsaconfigurationsectionthatspecifiesEnterpriseLibraryshouldreadconfigurationinformationusingtheFileConfigurationSource.XML
<enterpriseLibrary.ConfigurationSourceselectedSource="fileSource">
<sources>
<addname="fileSource"
type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource,
Microsoft.Practices.EnterpriseLibrary.Common"
filePath="test.exe.config"/>
<addname="systemSource"
type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource,
Microsoft.Practices.EnterpriseLibrary.Common"/>
</sources>
</enterpriseLibrary.ConfigurationSource>
![Page 78: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/78.jpg)
RedirectionandInheritanceConfigurationPropertyandAttributeSettings
![Page 79: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/79.jpg)
SavedConfigurationSettingsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 80: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/80.jpg)
MicrosoftEnterpriseLibrary5.0
UsingGroupPolicywithEnterpriseLibrary
GroupPolicyprovidesacentralizedone-to-manymanagementcapabilityforWindowsthatallowsadministratorstodefinesettingsthatapplytoagroupofcomputers,systems,services,orapplications.GroupPolicyreliesontheActiveDirectory®servicetomanagethesettingsappliedatruntimetomembersoftheActiveDirectoryforest,domain,orsubgroup.FormoreinformationaboutGroupPolicy,seeGroupPolicyonMSDN.
EnterpriseLibraryincludesamanageableconfigurationsource.ThisallowsyoutouseGroupPolicytomanageanEnterpriseLibraryapplication.Youdonotneedtowriteanyapplicationcodetousethesefeatures.ThistopicprovidesinformationaboutthefollowingtasksforusingGroupPolicy:
AddingaManageableConfigurationSourceGeneratingandInstallingGroupPolicyTemplatesTroubleshootingGroupPolicy
![Page 81: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/81.jpg)
AddingaManageableConfigurationSource
![Page 82: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/82.jpg)
GeneratingandInstallingGroupPolicyTemplates
![Page 83: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/83.jpg)
TroubleshootingGroupPolicy
![Page 84: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/84.jpg)
AdministratorEntersInvalidValues
![Page 85: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/85.jpg)
ApplicationIsModifiedWithoutGeneratingNewGroupPolicyTemplate
![Page 86: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/86.jpg)
PoliciesConflicttoProduceInvalidConfiguration
![Page 87: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/87.jpg)
OtherErrorsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 88: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/88.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringaDeploymentEnvironment
Youcanusetheconfigurationtoolsatdesigntimetocustomizetherun-timesettingsofyourconfigurationtosuitaparticulardeploymentenvironment.Thisfeatureisusefulifyouhavemultipleenvironmentsthatsharethesamebasicconfigurationbutrequiredifferentpropertysettings.Forexample,youmayhaveadevelopmentenvironmentthatusesoneconnectionstringfortheDataAccessApplicationBlockandatestenvironmentthatusesadifferentone.
Everyenvironmentyouconfiguremaintainsitsownenvironmentdeltafile(usingthefilenameextension.dconfig),whichisupdatedafteryousavetheconfiguration.Thisenvironmentdeltafilecontainsthedifferencesbetweenthisenvironmentandthestandardenvironment,plussomeadditionalmetadataformergingthedifferencesintoanewcompleteconfigurationfilethatyoucandeploy.Themainadvantageisthatyoucandistributeanenvironmentdeltafileseparatelyfromtheoriginalconfigurationfileandallowmanagementbyusersoradministratorswhohaveaccesstoallthepasswords,servernames,andotherdetailsofthatenvironment.
Therefore,insteadofmaintainingmultipleconfigurationfilesorhavingtochangeafilemanuallyorprogrammatically,youcancreateabaseconfigurationfile(.config)andanenvironmentdeltafilethatcontainsthedifferences(.dconfig).
Youcanuseenvironmentalpropertyoverridestooverridespecificpropertiesforablockandforthepropertiesofthechildelementsforablock,andthencreateadeploymentenvironmentbysavingtheconfigurationdelta.Thenyoucanexportthemergedconfigurationfileandcopyordeployittoproduction.
Thelifetimeofthemainconfigurationandthelifetimeoftheenvironmentaloverridesarelinkedonlythroughthestructureofthefiles.Thefollowingoperationscanbeperformedonenvironmentdeltafiles:
File|Save:Savingthemainconfigurationalsosavesanyrelatedenvironments.Theenvironment.dconfigfileissavedusingthepathspecifiedintheEnvironmentDeltaFilepropertyoftheenvironmentoverride.File|SaveAs:Specifyinganewpathornameonlyaffectsthemain
![Page 89: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/89.jpg)
configurationfile.YoumustchangethepathandnamespecifiedintheEnvironmentDeltaFilepropertyoftheenvironmentoverridetochangetheenvironmentnameandpath.File|New:Creatinganewconfigurationclearstheexistingconfigurationandallopenenvironments,createsanewemptyconfigurationfile,andclearsthevalidationresults.Youarepromptedtosavethefilebeingclearedifithasanychanges.Validation:Youcansaveconfigurationandenvironmentfilesonlyifallfilesarevalid.Eitherallaresavedornonearesaved.
Toopenorcreateaconfigurationfileinordertocreateadeploymentenvironment
1. ClickonOpenintheFilemenutoopenanexisting.configfile,orclickNewontheFilemenutocreateanewfile,andthenaddtheappropriatelyconfiguredapplicationblocksintheconfigurationtool.
2. Browsetotheconfigurationfileyouwantorthelocationwhereyouwanttosavethenewfile.
3. Selectaconfigurationfileandviewtheconfiguredapplicationblocks.
Tocustomizeablock'spropertiesforaruntimeenvironment1. OntheEnvironmentsmenu,clickNewEnvironmenttoopenanew
environmentconfigurationfile.Youmusthaveanenvironmentopeninorderforthepropertyoverridestobedisplayed.
2. ClicktheEnvironmentpropertyexpanderchevrontoopenorclosetheenvironmentpropertieseditpane.Note:
Youcanhavemultipleenvironmentconfigurationfilesopensimultaneously.Eachisdisplayedbyname.
![Page 90: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/90.jpg)
3. Intheeditpane,settheproperties.TheEnvironmentDeltaFilepropertyisthenameofthedeltafile.Ifyouwanttoencryptthefile,settheProtectionProviderpropertybyselectingaproviderfromthedrop-downlist.TheEnvironmentConfigurationFilepropertyisthenameofthemergedconfigurationfile.TheEnvironmentNamepropertyisthenameoftheenvironment.
4. Repeatthepreviousstepsforeachenvironmentyouwanttocreate.5. Tocustomizeablock'spropertiesforthisenvironment,addthe
applicationblocktotheconfiguration.OpentheBlocksmenuandselecttheblockyourequirebyclickingonitssettings;forexample,AddLoggingSettings.
![Page 91: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/91.jpg)
6. Clicktheblockspropertiesexpanderarrowtoviewthelistofproperties.IntheOverrideson[environmentname]drop-downbox,clickOverridePropertiestoenablesettingtheblock'spropertiesforthisenvironment.
![Page 92: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/92.jpg)
Note:Ifyourenameanenvironment,theupdatednamemaynotbedisplayedintheOverrideson[environmentname]property.However,itwillbeshownthenexttimeyouopentheconfigurationinthetool.
7. Clicktheexpanderarrowontheleftofthenamedenvironmentlistedundertheblock'sproperties,inthisscreenshottotheleftofOverridesonTestPlatform,todisplaythepropertiesforthatnamedenvironment.Youcanthenuseeachpropertydrop-downeditboxtoeditthepropertiesappropriatelyforyourrequirements.
![Page 93: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/93.jpg)
8. Repeatsteps4,5and6foreachblockyouwanttocustomize.
Note:Theconfigurationtoolallowsyoutoaddmorethanoneadditionalenvironment.Eachconfigureditemthendisplaysasetofpropertiesforthebaseconfigurationfileandasetofpropertiesspecifictoeachofthenamedenvironments(withtheexceptionofpropertiesthatcannotbeoverridden).Thisenablesyoutoeditthebaseconfigurationfilepropertiesorthedeltafilepropertiesforaspecificnamedenvironment.
Tocustomizeablock'schildelementpropertiesforarun-timeenvironment1. Clickonthechildexpanderarrowtotheleftoftheblockname
—LoggingSettingsinthisexample—todisplaythechildelementsiftheyarenotalreadyvisible.
2. Ineachofthechildelementsthatyouwanttoconfigurefordifferent
![Page 94: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/94.jpg)
environments,clickonthepropertyexpanderfortheenvironmentyouwanttoedit—OverridesonTestPlatforminthisexample.
3. SettheOverrideson[environmentname]propertytoOverrideProperties,andtheneditthepropertiesyouwanttooverrideforthatenvironment.ThisscreenshotshowshowyoucanspecifydifferentpropertyvaluesforaLoggingblockcategoryfilterandatargetlistenerindifferentenvironments.
Tosaveaconfiguration(.config)fileandadeltaenvironment(.dconfig)file1. SelectSaveorSaveAsontheFilemenutosaveboththenamed
environmentconfigurationfileandthedeltafile;ifeitherfilenameisblankyouwillbepromptedtoselectapathandfilename.
![Page 95: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/95.jpg)
CopyCode
2. ClickSave.Theconfigurationfileissavedandyouarepromptedforapathandnametosavethedeltaenvironmentfile.
3. ClickSaveAsandyouarepromptedfirstforapathandnametosavetheconfigurationfile.Thenyouarepromptedforapathandnametosavethedeltaenvironmentfile.
Tocreateamergedenvironmentconfigurationfile1. Right-clickonthenamedEnvironmentforwhichyouwanttocreatea
mergeddeploymentconfigurationfile,thenclickExportMergedEnvironmentConfigurationFile.
2. Tosavejustthedifferencesbetweenthemainandanenvironmentoverrideconfiguration,clickSaveEnvironmentDeltaFile.
Youcanalsomergeyourmainconfigurationfileandyourenvironmentdeltafilefromthecommandline.Thisisusefulifyouwanttousebuildscriptsorautomatedeployment.Tomergetheconfigurationfiles,youmustprovideboththemainconfigurationfileandtheenvironmentdeltafileinyourcommand.Thefollowingcommandshowsthesyntax.
MergeConfiguration.execonfigFiledeltaFile[mergedFile]
Theparametersarethefollowing:configFile.Thisisthemainconfigurationfile(.config).Itismergedwiththeenvironmentdeltafile.deltaFile.Thisistheenvironmentdeltafile(.dconfig).Itcontainstheinformationthatismergedintothemainconfigurationfile.mergedFile.Thisistheoutputfile.ThisfileresultsfrommergingconfigFilewithdeltaFile.IfyoudonotspecifythemergedFile,thefilenamestoredindeltaFileisused.
Note:Theenvironmentdeltafiles(.dconfig)youcreatemustbereloadedeachtimeyoucloseandreopentheconfigurationfile.
Toreloadanenvironmentdeltaconfigurationfile1. StarttheEnterpriseLibraryconfigurationconsoleoropenthe
configurationfileintheVisualStudioconfigurationeditor.Formore
![Page 96: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/96.jpg)
informationontheEnterpriseLibraryconfigurationconsoleseeUsingtheConfigurationTools.
2. OntheFilemenu,clickOpen.3. IntheOpendialogbox,browsetoandselecttheapplication.configfile
youwanttoreload.4. IntheEnterpriseLibraryconfigurationtool,left-clickEnvironments,
andthenclickOpenDeltaFile.5. IntheOpendialogbox,selecttheenvironmentdeltaconfiguration
(.dconfig)fileyouwanttoreload,andthenclicktheOpenbutton.6. SavethechangesthroughtheFilemenuortheright-clickshortcut
menuontheenvironmentitem,asdescribedinthepreviousprocedure.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 97: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/97.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheFluentConfigurationAPI
ItispossibletoprogrammaticallymanipulatethedefaultconfigurationclassesusedbyEnterpriseLibraryforthecore,instrumentation,andalloftheapplicationblocks.ThefluentinterfaceexposedbyEnterpriseLibraryisdesignedtofacilitatethisprocess.ThefluentinterfacecanbeusedforalloftheconfigurablefeaturesofinstrumentationandforalloftheEnterpriseLibraryapplicationblockswiththeexceptionoftheValidationandPolicyInjectionApplicationBlocks.
UsingthefluentconfigurationAPI,youcan:CreateconfigurationsourcestopasstoEnterpriseLibraryobjectsthatyoucreateinyourapplications.Createconfigurationsourcesforentiresectionsoftheconfiguration,suchasfortheExceptionHandlingApplicationBlockortheLoggingApplicationBlock.CreatethecompleteconfigurationforEnterpriseLibraryforanapplication.Createdifferentenvironment-specificconfigurationsforsectionsorforentireapplications;thismakesiteasiertodeployanapplicationtodifferentrun-timeenvironments.Modifytheconfigurationatruntime;perhapstotakeintoaccountexternalfactorsorchangestotheenvironment.
Effectively,thefluentconfigurationAPIallowsyoutospecifyasetofconfigurationsectionsprogrammaticallyand,ifrequired,mergethemwithotherconfigurationsettingsspecifiedinothersourcessuchasafileconfigurationsource.Italsoallowsyoutoprogrammaticallydefineabaseconfigurationthatcanbechangedfromanothersource,suchasafileconfigurationsource,whichprovidestheabilitytooverridepartsofthebaseconfiguration.
![Page 98: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/98.jpg)
WorkingWiththeFluentConfigurationAPIEnterpriseLibraryprovidestheConfigurationSourceBuilderclassthatactsasthebasisforcreatingconfigurationsources.Eachoftheblocks,andthecoreandinstrumentationfeaturesofEnterpriseLibrary,providesextensionstothisclassthatexposeafluentinterfaceandmakeiteasytocreateconfigurationsources.
ThegeneralapproachistocreateaninstanceoftheConfigurationSourceBuilderclassandthenspecifythesectionyouwanttoconfigure.Theextensionsforeachconfigurationsectionexposeintuitivemethodsthatallowyoutoaddtheappropriatepolicies,providers,orothertypesofextensionstotheconfigurationandspecifytherequiredconfigurationsettingsforeachone.InVisualStudio,theIntelliSense®featurewillhelpyoutolocateandusetheindividualmethodsavailableforeachconfigurationextension.Forexample,youcanconfigureinstrumentationforaconfigurationsourceusingthefollowingcode.C#
varbuilder=newConfigurationSourceBuilder();
builder.ConfigureInstrumentation()
.ForApplicationInstance("MyApp")
.EnableLogging()
.EnablePerformanceCounters();
varconfigSource=newDictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
=EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
VisualBasic
Dimbuilder=NewConfigurationSourceBuilder()
builder.ConfigureInstrumentation()_
.ForApplicationInstance("MyApp")_
.EnableLogging()_
![Page 99: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/99.jpg)
.EnablePerformanceCounters()_
DimconfigSource=NewDictionaryConfigurationSource()
builder.UpdateConfigurationWithReplace(configSource)
EnterpriseLibraryContainer.Current_
=EnterpriseLibraryContainer.CreateDefaultContainer(configSource)
Thefinallineinthiscodecreatesanewcontainerandassignstheconfigurationtoit.EnterpriseLibrarywillusethisconfigurationtoresolvetheobjectsitrequires.YoucanalsousethemethodsoftheIServiceLocatorinterfacetoobtaininstancesofEnterpriseLibraryobjectsondemandinyourcodebyaccessingtheIServiceLocatorimplementationthroughtheEnterpriseLibraryContainer.Currentproperty.
TheAPIalsoprovidesmethodsthatallowyoutocheckifaspecificsectionalreadyexistsintheconfiguration,andaddnewsectionstotheconfiguration.Forperformancereasons,thefluentconfigurationAPIdoesnotperformfullvaliditycheckingofthesettingsyouspecify.Itdoescheckfornullvalues,however.Toobtainfullvaliditychecking,youcanusethegraphicalconfigurationtoolstosetupandverifyyourconfiguration,andthentranslateitintocallstotheconfigurationAPI.
AllconfigurationsourceclassesimplementtheIConfigurationSourceinterface.Thisinterfaceallowsyourapplicationcodetosubscribetonotificationsofconfigurationchanges.Formoreinformation,seeUpdatingConfigurationSettingsatRunTime.Bydefault,inEnterpriseLibrary,onlytheLoggingApplicationBlockregisterstoreceivenotificationsofconfigurationchanges.
ThefollowingexamplesshowhowyoucanconfiguretheotherblocksinEnterpriseLibraryusingthefluentAPI:
TheCachingApplicationBlockTheCryptographyApplicationBlockTheDataAccessApplicationBlockTheExceptionHandlingBlockTheLoggingApplicationBlockTheSecurityApplicationBlock
![Page 100: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/100.jpg)
TheCachingApplicationBlock
![Page 101: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/101.jpg)
TheCryptographyApplicationBlock
![Page 102: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/102.jpg)
TheDataAccessApplicationBlock
![Page 103: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/103.jpg)
TheExceptionHandlingBlock
![Page 104: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/104.jpg)
TheLoggingApplicationBlock
![Page 105: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/105.jpg)
TheSecurityApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 106: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/106.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheappSettingsSection
YoucanusetheconfigurationtoolstocreateandmodifyMicrosoft.NETFramework<appSettings>sections.Notethatthe<appSettings>sectionsmustbeincludedinasinglefile;theyshouldnotbedistributedacrossmultiplefiles.ExamplesoffilesthatyoucannoteditincludetheMachine.configfileand<appSettings>sectionsthatincludetheoptionalfileattributethatspecifiesarelativepathtoanexternalconfigurationfile.
![Page 107: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/107.jpg)
Configurean<appSettings>SectionUsingtheConfigurationTool
![Page 108: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/108.jpg)
Configurean<appSettings>SectionbyEditingtheXMLToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 109: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/109.jpg)
MicrosoftEnterpriseLibrary5.0
UpdatingConfigurationSettingsatRunTime
ThedefaultconfigurationsystemincludedintheEnterpriseLibraryCoreis,withoneexception,read-only.Whenusingapplicationconfigurationfiles(App.configandWeb.config),updatestothesefilesdonotaffectexistinginstancesofobjects.However,newinstancescreatedafterchangesaremadetotheconfigurationfilewillreflectthesechanges.InWindowsFormsapplications,youcanrestarttheapplicationtocauseittoreadtheallofthenewconfigurationinformation.WebForms(ASP.NET)applicationswilldetectandreloadtheconfigurationinformation,butthestandardbehaviorofASP.NETcausestheapplicationtorestartwhenyouedittheconfigurationfile,whichcausesallstatetobelostfortheapplication.
TheoneexceptiontothisistheLoggingApplicationBlock,whichisabletodetectconfigurationchangesandreloadtheconfigurationwithoutrestartingtheapplication.ThisworksforWebFormsandWindowsFormsapplications,thoughitwillstillautomaticallytriggertheapplicationtorestartforWebFormsapplications.Thismeansthatyoucannotrelyonmaintenanceofin-processsessionstateinASP.NETapplicationswhenyouchangetheconfigurationfile.
![Page 110: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/110.jpg)
DetectingConfigurationChangesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 111: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/111.jpg)
MicrosoftEnterpriseLibrary5.0
EncryptingConfigurationData
Youcanencryptanddecryptthedatainaconfigurationfile'sconfigurationsections.Aconfigurationsectioncontainstheconfigurationinformationforanapplicationblock.TheconfigurationtoolallowsyoutoselectfromtheencryptionprovidersthatareincludedintheMachine.configfile.Typically,thesearetheDataProtectionConfigurationProvider,whichusestheWindowsdataprotectionAPI(DPAPI),andtheRsaProtectedConfigurationProvider,whichusesRSA.
Iftheencryptedconfigurationfileisgoingtobeononlyasingleserver,youcanusetheDataProtectionConfigurationProvider.IfyouwanttodeploythesameencryptedconfigurationfileonmultipleserversinaWebfarm,youshouldusetheRsaProtectedConfigurationProvider.ThisprovidermakesiteasyforyouencryptthedataononeservercomputerandthenexporttheRSAprivatekeyneededtodecryptthedata.Youcanthendeploytheconfigurationfileandtheexportedkeytothetargetservers,andthenre-importthekeys.
TheuseraccountusedforencryptingthefilewhenusingtheRsaProtectedConfigurationProvidermusthavetheappropriateminimalpermissions,whichmustincludereadpermissionsontheNetFrameworkConfigurationKeykeycontainer,inordertoencryptanddecryptsectionswhenusingtheEnterpriseLibraryconfigurationtools.Bydefault,thisincludesonlyadministrativeaccounts.
Theappropriateminimalpermissions,whichmustincludereadpermissions,arealsorequiredforruntimeandconfigurationmergesperformedwhenusingtheconfigurationtoolsandworkingwithconfigurationsectionsthathavebeenencryptedbyusingtheRsaProtectedConfigurationProvider.
FormoreinformationseeCreatingandExportinganRSAKeyContaineronMSDN.
Note:Wheneveryouchangesecuritysettingsandpermissions,besurethatyouareawareofanysecurityrisksraisedbygivingelevatedpermissions.
![Page 112: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/112.jpg)
Toencryptaconfigurationsection1. OpenoneoftheEnterpriseLibraryconfigurationtools.2. Openanexistingconfigurationfileorcreateanewone.3. Clickthechevronarrowattherightofnameoftheapplicationblock
whoseconfigurationinformationyouwanttoencrypt.4. InthePropertiespane,clickthedrop-downlistfortheProtection
Providerproperty.5. SelecteitherDataProtectionConfigurationProvideror
RsaProtectedConfigurationProvider.
Allthesettingsfortheproviders,suchaswherekeysarestored,arealsointheMachine.configfile.Youcannotchangethisfilewithaconfigurationtool.Instead,youmustmodifythefileusingatexteditor.
Todecryptaconfigurationfile,simplyopenitintheconfigurationtool.Thefileisautomaticallydecrypted.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 113: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/113.jpg)
MicrosoftEnterpriseLibrary5.0
EnablingInstrumentation
Theterminstrumentationreferstoasystem'sbuilt-inabilitytomonitorormeasureperformanceandtodiagnoseerrors.EnterpriseLibraryincorporatesthefollowinginstrumentationinthemajorityoftheapplicationblocks:
Eventlogs.Theapplicationblocksinformusersofkeyevents,suchaserrorsorwarnings.Performancecounters.Theapplicationblocksrecordkeymetrics—suchasthenumberofcriticaleventsthatoccurpersecondortheaveragetimeittakestocompletekeytasks—bywritingtotheMicrosoftWindows®operatingsystemperformancecounters.
FordetailsofthedesignoftheEnterpriseLibraryinstrumentation,seeInstrumentation.
![Page 114: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/114.jpg)
EnablingandDisablingInstrumentation
![Page 115: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/115.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 116: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/116.jpg)
MicrosoftEnterpriseLibrary5.0
SourceSchemaforEnterpriseLibraryCore
TheEnterpriseLibraryCoreprovidesservices,suchasinstrumentationandconfiguration,andallEnterpriseLibraryapplicationblocksexceptforUnityaredependentonthecore.ThecorelibraryfunctionalityiscontainedintheassemblyMicrosoft.Practices.EnterpriseLibrary.Common.dll.
TherearetwoconfigurationsectionsassociatedwiththeEnterpriseLibraryCore.TheyaretheinstrumentationConfigurationsectionandtheenterpriseLibrary.ConfigurationSourcesection.Thesesectionsdefinewhichtypesofinstrumentationareenabledintheapplication(ifany),andwhichconfigurationsourceshouldbeusedtoaccessconfigurationinformationwithintheapplication.ThefollowingXMLcodeshowstheconfigurationsectiondeclarationsthatdefinethelocationsoftheseconfigurationsections.Thesedeclarationsshouldbedefinedwithinthe<configSections>sectionoftheapplicationconfigurationfile.XML
<configSections>
<sectionname="instrumentationConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation.Configuration.InstrumentationConfigurationSection,
Microsoft.Practices.EnterpriseLibrary.Common"/>
<sectionname="enterpriseLibrary.ConfigurationSource"
type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection,
Microsoft.Practices.EnterpriseLibrary.Common"/>
</configSections>
IfthereisnoenterpriseLibrary.ConfigurationSourcesectionintheconfigurationfile,aninstanceoftheSystemConfigurationSourceclassbecomestheconfigurationsourcefortheapplication.ThismeansthatwhentheapplicationcreatesEnterpriseLibraryobjects,itretrievesconfigurationinformationfromtheapplicationconfigurationfile.
![Page 117: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/117.jpg)
enterpriseLibrary.ConfigurationSourceElement
![Page 118: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/118.jpg)
sourcesElement
![Page 119: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/119.jpg)
instrumentationConfigurationChildElementToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 120: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/120.jpg)
MicrosoftEnterpriseLibrary5.0
UsingEnterpriseLibraryinApplications
EnterpriseLibrarycanbeusedinmosttypesofapplicationsandinthemajorityofscenarioswhereyourequireaneasy-to-useyethighlyflexiblelibrarytohelpyoumanagecrosscuttingconcerns.Forexample,youcanuseEnterpriseLibraryinapplicationbuiltwithWindowsForms,WindowsPresentationFoundation(WPF),WindowsCommunicationFoundation(WCF),ASP.NET,Silverlight®,andconsole-basedapplications.YoucanalsouseEnterpriseLibraryinbothgreenfieldandbrownfieldscenarios.
Whenarchitectingnewapplications,EnterpriseLibrarycanbeusedtoimplementmanyofthecommondesignpatternsyouincorporateinyourdesign.Youcanplanforitsusethroughoutthelayersandcomponentsofyourapplication.YoucanalsouseEnterpriseLibrarysuccessfullyinexistingapplications,whereitcanhelptosimplifythetaskofupdatingoraddingnewfunctionality.Theconfigurationtoolsdonotaffectexistinginformationinyourapplicationconfigurationfiles,andtheassembliesandcodecanbeaddedtoexistingapplicationswithoutfearofconflicts.
EnterpriseLibraryincludessourcecodefortheapplicationblocks,andcompiledandsignedversionsoftheapplicationblockassemblies.Youcanusetheseassembliesdirectly,compiletheapplicationblocksandusethecompiledassemblies,orincludethesourcecodeinyourapplication.However,beforeyoucanusetheassembliesinyourapplication,youmustaddreferencestotherelevantapplicationblockassemblies,andtotheCommonandUnityassemblies.Then,towriteapplicationcode,youalsomustbeawareoftheEnterpriseLibrarynamespaceconventionsandobjectcreationpatterns.
ThissectioncontainsthefollowingtopicsthatwillhelpyoutogetstartedusingEnterpriseLibrary:
ReferencingEnterpriseLibraryAssemblies.Thistopicexplainshowtoaddreferencestotherequiredassembliestoyourapplication,andimporttheseintoyourprojects.DependenciesinEnterpriseLibrary.Thistopicexplainshowsomeoftheblocksdependonothers,andhowalloftheblocksdependoncorefeaturesofEnterpriseLibrary.Itwillhelpyoutounderstandwhichassembliesandfeaturesyourequiredependingontheblocksyouuseand
![Page 121: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/121.jpg)
yourownscenarios.CreatingandReferencingEnterpriseLibraryObjects.ThistopicdescribesthevariouswaysofaccessingEnterpriseLibraryobjects,whattheiradvantagesanddisadvantagesare,anddetailsofhowtheyworkintheunderlyingcode.
Forinformationabouthowtocompiletheapplicationblocks,seeBuildingEnterpriseLibraryfromtheSourceCode.Forinformationaboutthedesignofthedependencyinjectionmechanism,seeTheDependencyInjectionModel.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 122: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/122.jpg)
MicrosoftEnterpriseLibrary5.0
ReferencingEnterpriseLibraryAssemblies
BeforeyoucanbuildapplicationsthatincorporatetheEnterpriseLibraryapplicationblocks,youmustaddreferencestotheapplicationblockassembliesandtotheCommonandUnityassemblies.ThispreparesyourapplicationtousetheEnterpriseLibrary.TakecaretoselecttheassembliesthatreflectyourdecisiontousetheMicrosoftstrong-namedassemblies,orthenon-strong-namedassemblies,oracustomizedsetofEnterpriseLibraryassemblies.
Toprepareyourapplication1. Addareferencetotheapplicationblockassembly.InVisualStudio,
right-clickyourprojectnodeinSolutionExplorer,andthenclickAddReference.ClicktheBrowsetab,andthenfindthelocationoftheapplicationblockassembly(thescriptCopyAssemblies.batcopiesallapplicationblockassembliestothebinsubdirectory).Selecttheassembly,andthenclickOKtoaddthereference.Forexample,toreferencetheLoggingApplicationBlockassembly,browsetothebinsubdirectory,selecttheassemblyMicrosoft.Practices.EnterpriseLibrary.Logging.dll,andthenclickOK.
2. Usethesameproceduretosetareferencetothefollowingassemblies:Microsoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.Unity.dllMicrosoft.Practices.Unity.Interception.dll.
Note:YouwillalsoneedtheassemblyMicrosoft.Practices.Unity.Configuration.dllifyouwishtoreferencespecificUnityconfigurationclassesinyourcode.However,inthemajorityofcases,youwillnotrequirethisassembly.
![Page 123: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/123.jpg)
EnterpriseLibraryNamespacesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 124: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/124.jpg)
MicrosoftEnterpriseLibrary5.0
DependenciesinEnterpriseLibrary
ThistopicdescribesthedependenciesbetweentheblocksandonthecorefeaturesofEnterpriseLibrary.Itcontainsthefollowingsectionsthatdescribetheinter-blockdependenciesforcommonscenarios:
DependenciesforAllApplicationBlocksBlockDependencySchematicAdditionalDependenciesfortheCachingApplicationBlockAdditionalDependenciesfortheExceptionHandlingApplicationBlockAdditionalDependenciesforthePolicyInjectionApplicationBlockAdditionalDependenciesfortheSecurityApplicationBlock
![Page 125: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/125.jpg)
DependenciesforAllApplicationBlocks
![Page 126: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/126.jpg)
BlockDependencySchematic
![Page 127: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/127.jpg)
AdditionalDependenciesfortheCachingApplicationBlock
![Page 128: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/128.jpg)
AdditionalDependenciesfortheExceptionHandlingApplicationBlock
![Page 129: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/129.jpg)
AdditionalDependenciesforthePolicyInjectionApplicationBlock
![Page 130: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/130.jpg)
AdditionalDependenciesfortheSecurityApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 131: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/131.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingandReferencingEnterpriseLibraryObjects
ThistopicdiscussesthewaysyoucaninstantiateandaccessEnterpriseLibraryobjects,theadvantagesanddisadvantagesofeachapproach,andmoredetailsabouthowtheyworkintheunderlyingcode.EnterpriseLibraryoffersagreatdealoffunctionality,andmanydifferentwaystoaccessit.Thistopicisintendedtoclarifythechoicesandtohelpyoudeterminewhatwillworkbestforyourapplication.
Typically,youwillcreateinstancesofEnterpriseLibraryobjectsusingoneofthefollowingtwoapproaches:
UsingtheUnityServiceLocator.Thisisthesimplestapproach,andisrecommendedforsimpleapplicationsthathavefewdependencies,andwhereyoudonotwanttotakeadvantageofcontemporaryarchitecturalpatternssuchasdependencyinjection.Itrequiresnoinitializationorsetup.YousimplyconfigureyourapplicationtouseEnterpriseLibraryandthencallthemethodsoftheservicelocatortoobtaininstancesofEnterpriseLibrarytypesondemand.AccessingtheUnityContainerDirectly.Thismoresophisticatedapproachallowsyoutoobtainthefullbenefitsofcontemporaryarchitecturalpatternssuchasdependencyinjectionforyourlayers,components,andcustomtypes.Itrequiresonlyminimalsetup,butmayrequirethatyoumaintainareferencetothecontainerinyourapplication.
Whenyouuseeitheroftheseapproaches,youwilltypicallyrequestandobtainreferencestooneormorenon-staticobjectsandinterfacesthatarepartofeachapplicationblock,whichallowyoutoaccessthefunctionalityoftheblocksandobtaininstancesofEnterpriseLibraryobjectsinyourcodeusingbothdependencyinjectionandtheservicelocatorapproach.Foralistoftheseobjectsandinterfaces,seeNon-StaticInstancesandInstanceFactories.
OtherapproachestocreatingEnterpriseLibraryobjectsthatyoumaychooseinclude:
UsingadifferentservicelocatorifyoudecidetouseacontainerotherthanUnity.Formoreinformationabouthowtheservicelocatorworks,seeInitializingandSettingtheCurrentContainer.FormoreinformationaboutreplacingthedefaultUnitycontainer,seeTheDependency
![Page 132: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/132.jpg)
InjectionModelinthesection"DesignofEnterpriseLibrary".UsingthelegacystaticfacadesandfactoriesthatwerethedefaultapproachinpreviousversionsofEnterpriseLibrary.Formoreinformationaboutthese,seeLegacyStaticFacadesandFactories.
![Page 133: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/133.jpg)
UsingtheUnityServiceLocator
![Page 134: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/134.jpg)
AccessingtheUnityContainerDirectly
![Page 135: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/135.jpg)
Non-StaticInstancesandInstanceFactories
![Page 136: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/136.jpg)
LegacyStaticFacadesandFactories
![Page 137: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/137.jpg)
InitializingandSettingtheCurrentContainer
![Page 138: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/138.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 139: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/139.jpg)
MicrosoftEnterpriseLibrary5.0
StoringaReferencetotheContainer
Typically,ifyoudonotuseconstructor,property,ormethodcallinjectiontoresolveandpopulateallofyourapplicationdependenciesduringinitialization,youwillneedtoretainareferencetothecontainerifyouwishtoaccessitdirectlytoresolveobjects.However,therearesomeothersituationsinwhichyoumaywanttobeabletoreferencethecontainerafterinitialization.Thefollowingaresomescenariosinwhichyoumayconsiderstoringareferencetothecontainerforuseinyourcode:
IfyouareusingASP.NETWebFormsorbuildingaWebservice.Youmustbeabletoresolveobjectsforeachpageorservicerequest,anditisquiteexpensiveintermsofresourcesanddoesnotmakesensetocreatethecontainerandloadtheEnterpriseLibraryconfigurationinformationoryourowncustomregistrationseverytime.Inthiscase,youwillusuallystorethepopulatedcontainerintheASP.NETApplicationdictionaryorwithinyourserviceimplementationanduseittoresolveinstancesasrequiredforeachrequest.Ifyouarecreatingaconsoleapplicationoracomponent(ratherthananapplicationwithauserinterfaceoraWebservice).IfyouareusingUnityasyourcontainer,youcancreatethecontainerandloadtheEnterpriseLibrarycontainerextensioninyourstartupcodeandthenuseittoresolvethedependenciesofotherclassesondemandusingtheResolvemethod.Anydependenciesdefinedintheseclasseswillbepopulatedautomatically.Youcanholditinaglobalvariablethroughoutthelifeoftheapplication.Notethatdisposingthecontainerisnotrecommended.Ifyouwanttostoreregistrationsforyourownobjectswithinthecontainer.Youmaychoosetouseaseparatecontainerforthis,thoughyoucanjustaseasilymakeuseofthedefaultcontainerthatholdstheEnterpriseLibraryconfigurationregistrations.Ifyouwanttobeabletoresolveinstancesofobjectsondemandratherthatalwayshavingthemresolvedwhenaclassisinstantiated.Forexample,ifanobjectisonlyrequiredincertaincases(perhapsbasedontherun-timeenvironmentorsomeotherfactor),itmaybeusefultobeabletocallthemethodsthatresolveinstancesfromthecontaineratrun
![Page 140: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/140.jpg)
timeinsteadofusingconstructor,property,ormethodcallinjectiontocreatethemwhentheclassisinitialized.
Thefollowingtablewillhelpyoutounderstandwhenandwhereyoushouldholdareferencetothecontainerinforms-basedandrichclientapplicationsbuiltusingtechnologiessuchasWindowsForms,WindowsPresentationFoundation,andSilverlight.
Task When Where
Createandconfigurecontainer.
Atapplicationstartup.
Mainroutine,startupevents,applicationdefinitionfile,orasappropriateforthetechnology.
Obtainobjectsfromthecontainer.
Atapplicationstartup,andlaterifrequired.
Whereappropriateinthecode.
Storeareferencetothecontainer.
Atapplicationstartup.
Globalapplicationstate.
Disposethecontainer.
Whentheapplicationshutsdown.
Whereappropriateinthecodeorautomaticallywhentheapplicationends.
Thefollowingtablewillhelpyoutounderstandwhenandwhereyoushouldholdareferencetothecontainerinrequest-basedapplicationsbuiltusingtechnologiessuchasASP.NETWebapplicationsandWebservices.
Task When Where
Createandconfigurecontainer.
Atapplicationstartup.
HTTPModule(ASP.NETandASMX),InstanceContextextension(WCF).
Obtainobjectsfromthecontainer.
DuringeachHTTPrequest.
Intherequeststarteventorloadevent.Objectsaredisposedwhentherequestends.
Storeareferencetothe
Atapplicationstartup.
Globalapplicationstateorservicecontext.
![Page 141: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/141.jpg)
container.
Disposethecontainer.
Whentheapplicationshutsdown.
Whereappropriateinthecode.
![Page 142: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/142.jpg)
ResolvinganEntireObjectGraphatApplicationStartup
![Page 143: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/143.jpg)
ResolvingandInjectingObjectsonDemand
![Page 144: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/144.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 145: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/145.jpg)
MicrosoftEnterpriseLibrary5.0
WindowsFormsandWPFApplications
Althoughtheyareverydifferenttechnologies,WindowsFormsandWindowsPresentationFoundation(WPF)sharesomefundamentalcharacteristics.Inparticular,theybothusewindowobjectstoimplementtheuserinterfaceandallowyoutospecifywhichcodeshouldrunwhentheapplicationstartsup.Bydefault,thestartupcodesimplyloadsandshowsthemainwindow,butyoucaneasilymodifythistocreateaUnitycontainer,populateitwiththeEnterpriseLibraryconfigurationinformation,andresolvetheobjectsusedbytheapplication.
Forexample,youmaynotwishtocreateallofthewindowsatstartuptominimizestartuptimesormemoryusage.Youcanstoreareferencetothecontaineranduseittoresolvewindowsandothertypesondemand.
Thefollowingsectionscontainmoredetails:WindowsFormsApplicationsWindowsPresentationFoundationApplications
![Page 146: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/146.jpg)
WindowsFormsApplications
![Page 147: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/147.jpg)
WindowsPresentationFoundationApplications
![Page 148: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/148.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 149: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/149.jpg)
MicrosoftEnterpriseLibrary5.0
ASP.NETWebFormsApplications
InASP.NETWebFormsapplications,therecommendedapproachistostorethecontainerintheglobalstateprovidedbytheApplicationdictionaryobject.Youcanthenaccessthecontainerwhenrequiredor—evenbetter—useanHTTPmoduletoperforminjectiononallofthecontrolsinthepageautomatically.
Ingeneral,youshouldusetheApplicationdictionaryobjecttostorethesingleinstanceofthecontainer.YoumaydecidetocreatechildcontainersofthemaincontainerandstorethemineachuserSessionobject,orevenforeachrequest,toregisteryourcustomtypesandmappingsinthechildcontainers.However,thismayreduceapplicationperformance,andyoushouldgenerallyavoidcreatingadditionalcontainersifpossible.
ThefollowingsectionsdescribethetechniquesandlimitationsforinstantiatingthecontainerinASP.NETapplications.TheyincludeabasicandsimpleapproachtousingtheApplicationobjecttostorethecontainer,followedbytherecommendedapproachthat—whilemorecomplicated—willperforminjectiononthecontrolsinyourpageautomaticallyatruntime:
TheBasicApproach.Thisisthesimplestapproach,whichmaybesuitableinsmallapplicationswherediscoverabilityandtestabilityarelessofaconcern.RecommendedApproachforDependencyInjection.Thistechniquecanperforminjectiononthecontrolsinyourpageautomaticallyatruntime,andprovidebetterdiscoverabilityandtestability.LimitationsandAlternativeApproaches.ThissectiondescribessomeoftheissuesyoushouldbeawareofwhenusingthecontainerinASP.NETapplications.
![Page 150: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/150.jpg)
TheBasicApproach
![Page 151: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/151.jpg)
RecommendedApproachforDependencyInjection
![Page 152: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/152.jpg)
LimitationsandAlternativeApproachesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 153: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/153.jpg)
MicrosoftEnterpriseLibrary5.0
ASP.NETDependencyInjectionHTTPModule
YoucanuseanHTTPmodule,anextensiontotheASP.NETHttpApplicationStateclass,andcodeinGlobal.asaxtoforceASP.NETtoautomaticallyinjectdependentobjectsateverypagerequest,asdiscussedinthetopicASP.NETWebFormsApplications.
ThefollowingcodeshowsasuitableHTTPmodulethatcapturesthePreRequestHandlerExecuteeventtoinsertitselfintotheASP.NETexecutionpipeline.Oneachpagerequest,thehandlerresolvesthecurrentHTTPhandlerthroughthecontainerusingtheBuildUpmethodandthencapturestheOnPageInitCompleteevent.WhentheOnPageInitCompleteexecutes,themodulecodewalksthecompletecontroltree,resolvingeachcontrolthroughthecontainerusingtheBuildUpmethod.
TheBuildUpmethodtakesanexistingobjectinstance,resolvesandpopulatesanydependenciesspecifiedfortheclass,andthenreturnstheinstance.Iftherearenodependencies,itsimplyreturnstheoriginalinstance.C#
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingMicrosoft.Practices.Unity;
namespaceUnity.Web
{
publicclassUnityHttpModule:IHttpModule
{
publicvoidInit(HttpApplicationcontext)
{
context.PreRequestHandlerExecute+=OnPreRequestHandlerExecute;
}
publicvoidDispose(){}
![Page 154: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/154.jpg)
privatevoidOnPreRequestHandlerExecute(objectsender,EventArgse)
{
IHttpHandlercurrentHandler=HttpContext.Current.Handler;
HttpContext.Current.Application.GetContainer().BuildUp(
currentHandler.GetType(),currentHandler);
//UserControlsarereadytobebuiltupafterpageinitializationiscomplete
varcurrentPage=HttpContext.Current.HandlerasPage;
if(currentPage!=null)
{
currentPage.InitComplete+=OnPageInitComplete;
}
}
//Buildupeachcontrolinthepage'scontroltree
privatevoidOnPageInitComplete(objectsender,EventArgse)
{
varcurrentPage=(Page)sender;
IUnityContainercontainer=HttpContext.Current.Application.GetContainer();
foreach(ControlcinGetControlTree(currentPage))
{
container.BuildUp(c.GetType(),c);
}
context.PreRequestHandlerExecute-=OnPreRequestHandlerExecute;
}
//Getthecontrolsinthepage'scontroltreeexcludingthepageitself
privateIEnumerable<Control>GetControlTree(Controlroot)
{
foreach(Controlchildinroot.Controls)
{
yieldreturnchild;
foreach(ControlcinGetControlTree(child))
{
yieldreturnc;
}
}
}
}
![Page 155: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/155.jpg)
}
VisualBasic
ImportsSystem
ImportsSystem.Collections.Generic
ImportsSystem.Web
ImportsSystem.Web.UI
ImportsMicrosoft.Practices.Unity
NamespaceUnity.Web
PublicClassUnityHttpModule
ImplementsIHttpModule
PublicSubInit(ByValcontextAsHttpApplication)_
ImplementsSystem.Web.IHttpModule.Init
AddHandlercontext.PreRequestHandlerExecute,AddressOfOnPreRequestHandlerExecute
EndSub
PublicSubDispose()ImplementsSystem.Web.IHttpModule.Dispose
EndSub
PrivateSubOnPreRequestHandlerExecute(ByValsenderAsObject,ByValeAsEventArgs)
DimcurrentHandlerAsIHttpHandler=HttpContext.Current.Handler
HttpContext.Current.Application.GetContainer().BuildUp(_
currentHandler.[GetType](),currentHandler)
'UserControlsarereadytobebuiltupafterpageinitializationiscomplete
DimcurrentPage=TryCast(HttpContext.Current.Handler,Page)
IfNotcurrentPageIsNothingThen
AddHandlercurrentPage.InitComplete,AddressOfOnPageInitComplete
EndIf
EndSub
'Buildupeachcontrolinthepage'scontroltree
PrivateSubOnPageInitComplete(ByValsenderAsObject,ByValeAsEventArgs)
DimcurrentPage=DirectCast(sender,Page)
DimcontainerAsIUnityContainer=_HttpContext.Current.Application.GetContainer()
![Page 156: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/156.jpg)
ForEachcAsControlInGetControlTree(currentPage)
container.BuildUp(c.[GetType](),c)
Next
RemoveHandlercontext.PreRequestHandlerExecute,AddressOfOnPreRequestHandlerExecute
EndSub
'Getthecontrolsinthepage'scontroltreeexcludingthepageitself
PrivateFunctionGetControlTree(ByValrootAsControl)AsIEnumerable(OfControl)
DimcontrolListAsNewList(OfControl)
ForEachchildAsControlInroot.Controls
IfchildIsNothingThen
ExitFor
Else
controlList.Add(child)
EndIf
ForEachcAsControlInGetControlTree(child)
IfchildIsNothingThen
ExitFor
Else
controlList.Add(child)
EndIf
Next
Next
ReturncontrolList
EndFunction
EndClass
EndNamespace
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 157: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/157.jpg)
MicrosoftEnterpriseLibrary5.0
ASP.NETApplicationStateExtension
YoucanuseanHTTPmodule,anextensiontotheASP.NETHttpApplicationStateclass,andcodeinGlobal.asaxtoforceASP.NETtoautomaticallyinjectdependentobjectsateverypagerequest,asdiscussedinthetopicASP.NETWebFormsApplications.
ThefollowingshowsasuitableimplementationofanapplicationstateextensionthatexposesastaticGetContainermethod.ThemethodcreatesanewUnitycontainerintheApplicationstateifonedoesnotalreadyexist,orreturnsareferencetotheexistinginstance.C#
usingSystem.Web;
usingMicrosoft.Practices.Unity;
namespaceUnity.Web
{
publicstaticclassHttpApplicationStateExtensions
{
privateconststringGlobalContainerKey="EntLibContainer";
publicstaticIUnityContainerGetContainer(thisHttpApplicationStateappState)
{
appState.Lock();
try
{
varmyContainer=appState[GlobalContainerKey]asIUnityContainer;
if(myContainer==null)
{
myContainer=newUnityContainer();
appState[GlobalContainerKey]=myContainer;
}
returnmyContainer;
}
finally
![Page 158: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/158.jpg)
{
appState.UnLock();
}
}
}
}
VisualBasic
ImportsSystem.Web
ImportsMicrosoft.Practices.Unity
NamespaceUnity.Web
PublicModuleHttpApplicationStateExtensions
PrivateConstGlobalContainerKeyAsString="EntLibContainer"
<System.Runtime.CompilerServices.Extension>_
PublicSharedFunctionGetContainer(appStateAsHttpApplicationState)AsIUnityContainer
appState.Lock()
Try
DimmyContainer=TryCast(appState(GlobalContainerKey),IUnityContainer)
IfmyContainerIsNothingThen
myContainer=NewUnityContainer()
appState(GlobalContainerKey)=myContainer
EndIf
ReturnmyContainer
Finally
appState.UnLock()
EndTry
EndFunction
EndModule
EndNamespace
![Page 159: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/159.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 160: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/160.jpg)
MicrosoftEnterpriseLibrary5.0
WCFandASP.NETWebServiceApplications
ToinitializethecontainerandpopulatedependenciesinaWebserviceapplicationrequiresadifferentapproachfromthetypesofapplicationsthatexposeauserinterface(suchasWindowsForms,WPF,andASP.NETWebForms).ThistopicdescribesapossiblesolutionforASP.NETWebservices(ASMX),andpointstoresourcesthatwillhelpyouimplementtheprocessinaWindowsCommunicationFoundation(WCF)application.
![Page 161: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/161.jpg)
ASP.NETWebServiceApplications
![Page 162: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/162.jpg)
WCFApplicationsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 163: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/163.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingApplicationBlockObjects
YoucanresolveinstancesofbothEnterpriseLibraryobjectsandyourowncustomclassesusingthecontainer.TounderstandhowtoresolvetheappropriateEnterpriseLibraryobjects,youmustbeawareofthewaythattheEnterpriseLibraryconfigurationinformationforyourapplicationmapstotheregistrationsinthecontainer.
![Page 164: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/164.jpg)
DefaultandNamedObjectRegistrationsMostoftheEnterpriseLibraryapplicationblocksuseplug-inproviderstoaccomplishtheirtasks,whileprovidingtheflexibilityrequiredforuseinthewidestrangeofscenariosandenvironments.Forexample,youmightaddtwocachemanagerstotheCachingApplicationBlock;onethataccessesadatabasebackingstore,andonethatusesthelocalIsolatedStoragemechanism.IfyouusetheDataAccessApplicationBlock,youmightdefineseveralconnectionstodifferentdatabases,dependingontherequirementsofyourapplication.
Eachproviderisidentifiedbyaname,andthemappingsbetweentheproviderinterfaceorbaseclassandtheconcreteimplementationsoftheprovidersaredifferentiatedbythisname.Anapplicationconfigurationmay,forexample,definetwocachemanagers,DBStoreandLocalStore,whiletheDataAccessApplicationBlockconfigurationmaycontainmappingsnamedCustomerDB,SalesDB,andProductsDB.
Whenyoucreateinstancesoftheseobjectsusinganyoftheapproachesshownintherelatedtopicslistedbelow,youmustprovidethenametoselecttheappropriateobject.However,EnterpriseLibraryalsohastheconceptofadefaultproviderformostoftheblocks.Thisisspecifiedintheconfiguration,anddefinestheproviderthattheblockwilluseifyoudonotspecifyanamedprovider.Whenyouresolveatypewithoutprovidinganame,thecontainerwillreturnaninstanceofthedefaultproviderifitisspecifiedfortheblock.Thisisausefulfeaturethatmakesiteasytoswitchtheapplicationtouseadifferentproviderbyjustchangingthedefaultfortheblockintheconfigurationfile.
Forinformationaboutconfiguringdefaultandnamedproviders,seethetopic"EnteringConfigurationInformation"inthesection"DevelopingApplications"foreachoftheapplicationblocks.
![Page 165: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/165.jpg)
CreatingandResolvingObjectsThefollowingtopicsdescribeinmoredetailthethreemainscenariosforcreatingorinjectinginstancesofobjects:
InjectingResolvedTypesintoOtherClassesResolvingInstancesofTypesUsingUnityCreatingApplicationBlockObjectsDirectly
FordetailsonhowtocreateandreferenceobjectsseeCreatingandReferencingEnterpriseLibraryObjects.ForinformationaboutinitializingtheEnterpriseLibrarycontainerand—ifrequired—storingareferencetoit,seeStoringaReferencetotheContainer.
Note:PreviousversionsofEnterpriseLibraryusedstaticfactorymethodstocreateapplicationblockobjects.ThestaticfacadesandstatictypesareincludedinthisversionofEnterpriseLibrary,andexistingcodethatusesthemwillcontinuetowork.Formoreinformationaboutusingthestaticfacadesandstatictypes,seetheonlineguidanceathttp://msdn.microsoft.com/entlib/.
OnepointtonoteifyouarefamiliarwiththeproviderfactoryapproachforgeneratinginstancesofobjectsusedinversionsofEnterpriseLibrarypriortoversion5.0isthatthestaticfacadesusedintheseearlierversionscannotbeinjected.Newnon-staticfacadesareincludedinthisversionofEnterpriseLibrary.
FormoreinformationaboutUnity,seeUnityDependencyInjectionandInterception.FordetailsofhowUnityintegrateswiththeunderlyingconfigurationmechanisminEnterpriseLibrary,seeTheDependencyInjectionModel.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 166: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/166.jpg)
MicrosoftEnterpriseLibrary5.0
InjectingResolvedTypesintoOtherClasses
OneofthemajoradvantagesprovidedbydependencyinjectionmechanismssuchasUnityistheabilitytoautomaticallyinjectresolvedinstancesoftypesintootherclassesatruntime.Thisisthepreferredapproach,asitprovidesseveraladvantagesoverothertechniques(fordetailsoftheseadvantages,seeCreatingandReferencingEnterpriseLibraryObjects.)
Unitysupportsinjectionintotheparametersofconstructorsandmethods,andtosetthevalueofproperties.ThismeansthatyoucaneasilyinjectinstancesoftheEnterpriseLibraryobjectsandyourowncomponentsandservicesintocustombusinessobjectsandothercomponents.Thefollowingsectionsofthistopicprovidemoreinformation:
UsingConstructorInjectionUsingProperty(Setter)InjectionUsingMethodCallInjection
Note:OthertopicsinthissectionshowhowyoucanresolveinstancesofEnterpriseLibraryobjectsondemand,andhowyoucancreateinstancesofEnterpriseLibraryobjectsdirectly.Formoreinformation,seeResolvingInstancesofTypesUsingUnityandCreatingApplicationBlockObjectsDirectly.
Usingconstructor,method,andpropertyinjectionallowsyoutoinjectinstancesofresolvedtypesnotonlyintothetargettype(thetypeyouareactuallyresolving),butitalsopopulatesdependenciesinallresolvedtypes.Thefollowingschematicshowsanoverviewoftheprocess.
![Page 167: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/167.jpg)
FormoredetailedinformationaboutthedependencyinjectionfeaturesofUnity,seeUnityDependencyInjectionandInterception.
![Page 168: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/168.jpg)
UsingConstructorInjection
![Page 169: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/169.jpg)
UsingPropertyInjection
![Page 170: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/170.jpg)
UsingMethodCallInjectionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 171: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/171.jpg)
MicrosoftEnterpriseLibrary5.0
ResolvingInstancesofTypesUsingUnity
ThistopicdiscussesthemethodsthatUnityprovidesforresolvingtypesandcreatinginstancesoftypes.ItalsodescribeshowyoucanresolveinstancesofEnterpriseLibraryobjectsandyourowncustomtypes.Thetopicsarethefollowing:
TheUnityResolveMethodResolvingInstancesofEnterpriseLibraryTypesResolvingInstancesofYourOwnCustomTypes
Note:Othertopicsinthissectionshowhowyoucaninjectresolvedinstancesintoyourowncustomclasses,andhowyoucancreateinstancesofEnterpriseLibraryobjectsdirectly.Formoreinformation,seeInjectingResolvedTypesintoOtherClassesandCreatingApplicationBlockObjectsDirectly.
![Page 172: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/172.jpg)
TheUnityResolveMethod
![Page 174: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/174.jpg)
ResolvingInstancesofYourOwnCustomTypesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 175: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/175.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingApplicationBlockObjectsDirectly
Therearetimeswhentheconfigurationinformationforyourapplicationscenariodoesnotresideinaconfigurationsource.Forexample,yoursystemmaydynamicallycreateconfigurationinformationfromdataenteredbyauser.Forthesesituations,youcandirectlyconstructapplicationblockobjects,passingtherequiredconfigurationinformationtotheconstructor.
Note:Othertopicsinthissectionshowhowyoucaninjectresolvedinstancesintoyourowncustomclasses,andhowyoucanresolveinstancesofEnterpriseLibraryobjectsondemand.Formoreinformation,seeInjectingResolvedTypesintoOtherClassesandResolvingInstancesofTypesUsingUnity.
Whenyouconstructanapplicationblockobject,youmustconstructaspecificproviderimplementationtypeusingtheappropriateconstructorparametersandpasstherequiredargumentstotheconstructor.ThefollowingcodeshowshowtoconstructtheDataAccessApplicationBlockSqlDatabaseobject.C#
StringconnString=@"server=(local)\SQLEXPRESS;database=EntLibTest;"+"IntegratedSecurity=true";
SqlDatabasedb=newSqlDatabase(connString);
VisualBasic
DimconnStringAs[String]="server=(local)\SQLEXPRESS;database=EntLibTest;"+_
"IntegratedSecurity=true"
DimdbAsNewSqlDatabase(connString)
![Page 176: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/176.jpg)
ConfigurationInformationforNewObjectsSomeobjectconstructorshaveanoverloadthatacceptsaninstanceofaconfigurationsourcethatimplementstheIConfigurationSourceinterface.Thisallowsyoutosupplyconfigurationinformationdirectlytothenewobject.
![Page 177: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/177.jpg)
DependencyInjectionforExistingObjectsWhenyoucreateinstancesofobjectswithoutusingtheUnitydependencyinjectionmechanism,dependentobjectsarenotautomaticallyinjectedintoyournewobject.However,youcanforceUnitytoresolveandpopulatedependenciesbyusingtheBuildUpmethodofthecontainer.KeepinmindthatconstructorinjectiondoesnottakeplacewhenyouusetheBuildUpmethodbecausetheobjectalreadyexistsandsotheconstructordoesnotexecute.
ThefollowingexampleshowshowyoucanusetheBuildUpmethodtoapplydependencyinjectiontoanexistingobjectinstancenamedmyDataServicethatimplementstheinterfaceIMyService.FormoreinformationabouttheBuildUpmethod,seeUsingBuildUptoWireUpObjectsNotCreatedbytheContainerintheUnitydocumentation.C#
IMyServicemyDataService=newDataService();
IMyServicebuiltupDataService=container.BuildUp<IMyService>(myDataService);
VisualBasic
DimmyDataServiceAsIMyService=NewDataService()
DimbuiltupDataServiceAsIMyService=container.BuildUp(OfIMyService)(myDataService)
Note:EnterpriseLibraryincludescodetoenableinstrumentation.Ifyoudirectlyconstructapplicationblockobjects,instrumentationwillnotbeenabledforthoseobjects.However,inmostcases,youcanbindtheappropriateinstrumentationproviderstotheapplicationproviders.Formoreinformationaboutinstrumentationlistenersandinstrumentationproviders,seeEnablingInstrumentation.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,pleasesendemailto
![Page 178: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/178.jpg)
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 179: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/179.jpg)
MicrosoftEnterpriseLibrary5.0
DeployingEnterpriseLibrary
TheEnterpriseLibraryApplicationBlocksarecomprisedofmultipleassemblies.EachassemblythatbelongstotheEnterpriseLibrary(excludingUnity,whichisagenericutility)hasafilenamethatbeginswithMicrosoft.Practices.EnterpriseLibrary.Additionally,theapplicationblocksmaydependontheEnterpriseLibrarycommonassemblies.Anapplicationthatusesoneormoreoftheapplicationblocksmayhavedependenciesonotherapplicationblocks.Forexample,someapplicationsthatusetheCachingApplicationBlockalsorequiretheDataAccessApplicationBlockassemblies.ForinformationaboutthedependenciesbetweentheapplicationblocksandtheEnterpriseLibraryCore,seeDependenciesinEnterpriseLibrary.
AnapplicationthatusestheEnterpriseLibraryapplicationblockscanbedeployedinoneoftwoconfigurations:
Asprivateassembliesintheapplicationfolderhierarchy.Assharedassembliesinanyfilesystemlocationorintheglobalassemblycache.
Specificdeploymentrecommendationsareincludedinthedocumentationforeachapplicationblock.Formoreinformation,seethedeploymenttopicfortheindividualapplicationblock.ForgeneralinformationaboutpreparingandversioningEnterpriseLibraryandusingtheglobalassemblycache,seePreparationandVersioning.
Note:IfyoudecidetolocatetheEnterpriseLibraryassembliesintheglobalassemblycache,therearesomeextrastepsyoumusttakeifyouusetheDataAccessApplicationBlockandtheValidationApplicationBlock.Thesearedescribedinthesection"UsingtheGlobalAssemblyCache"inthetopicPreparationandVersioning,andathttp://entlib.codeplex.com/WorkItem/View.aspx?WorkItemId=26903.
EnterpriseLibraryincludespre-compiledstrong-namedassembliesforallthesourcecode.TheassembliesaresignedwithaMicrosoftstrong-namingkeythat
![Page 180: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/180.jpg)
isnotincludedwiththesourcecode.Thismeansthatyoucannotbuildacompiledversionfromthesourcecodethatusesthesamepublickey.However,youcanuseyourownkeypairtocreatestrong-namedassemblies.IfyoubelievethatyoumaycustomizetheEnterpriseLibrarysourcecode,youshouldusethebinariesthatyoucompilefromthesourcecodeandsignwithyourownkeyinsteadofusingthepre-compiledbinariessignedwiththeMicrosoftkey.
Formoreinformation,seeBuildingEnterpriseLibraryfromtheSourceCodeandStrongNamingtheEnterpriseLibraryAssemblies.
Ifyouupdateanyoftheapplicationblocks,orifyouwanttoinstallanupdatedversionofanassembly,youcaninstallthenewversionandhaveallapplicationsusetheupdatedassembly.Alternatively,youcaninstallthenewversionintheglobalassemblycacheandconfiguresomeapplicationstousetheupdatedversion,whileotherscontinuetousetheearlierversion.Formoredetails,seeUpdatingApplicationBlockAssemblies.
Ifyouintendtorunyourapplicationinpartialtrustenvironments,inparticularusingacustomizedASP.NETMediumTrustmode,seePartialTrustEnvironments.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 181: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/181.jpg)
MicrosoftEnterpriseLibrary5.0
PreparationandVersioning
WhenyoucompiletheinstalledversionoftheEnterpriseLibrarysourcecode,theassembliesproducedwillnotbestrongnamed.Asaresult,theycannotbeinstalledintheglobalassemblycache,norwilltheyhavetheotherbenefitsassociatedwithstrong-namedassemblies.
![Page 182: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/182.jpg)
UsingXCopy
![Page 183: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/183.jpg)
UsingtheGlobalAssemblyCache
![Page 184: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/184.jpg)
VersioningToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 185: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/185.jpg)
MicrosoftEnterpriseLibrary5.0
BuildingEnterpriseLibraryfromtheSourceCode
AlthoughtheEnterpriseLibraryincludesbinariesforallthesourcecode,youmaywanttocustomizethesourcecode.ThismeansyouwillneedtobuildtheEnterpriseLibraryyourself.Thefollowingsectionsdescribehowtodothis.Afteryouhavethebinaries,youmaywanttostrongnamethem.Formoreinformationaboutthistopic,seeStrongNamingtheEnterpriseLibraryAssemblies.
Thistopiccontainsthefollowingsubsections:InstallingtheSourceCodeEnterpriseLibraryVisualStudioSolutionFilesBuildingtheEnterpriseLibraryApplicationBlocksandToolsBuildingtheEnterpriseLibraryUsingMicrosoft.NetFramework4.0AdditionalNotesforBuildingandUsingtheSourceCode
![Page 186: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/186.jpg)
InstallingtheSourceCode
![Page 187: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/187.jpg)
EnterpriseLibraryVisualStudioSolutionFiles
![Page 188: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/188.jpg)
BuildingtheEnterpriseLibraryApplicationBlocksandTools
![Page 189: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/189.jpg)
AdditionalNotesforBuildingandUsingtheSourceCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 190: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/190.jpg)
MicrosoftEnterpriseLibrary5.0
StrongNamingtheEnterpriseLibraryAssemblies
IfyoubuildEnterpriseLibraryfromthesourcecode,youmaydecidetoapplystrongnamingtotheassemblies.Astrongnameconsistsoftheassembly'sidentity—thesimpletextname,versionnumber,andcultureinformation(ifprovided)—plusapublickeyandadigitalsignature.Thestrongnameisgeneratedfromanassemblyfile(thefilethatcontainstheassemblymanifest,whichinturncontainsthenamesandhashesofallthefilesthatmakeuptheassembly),usingthecorrespondingprivatekey.Signinganassemblywithastrongnameensuresthatitsnameisgloballyunique.Assemblieswiththesamestrongnameareexpectedtobeidentical.
Forexample,ifyouintendtosharetheEnterpriseLibraryassembliesamongseveralapplications,youcaninstallthemintotheglobalassemblycache.EachassemblyintheGACmusthaveagloballyuniquename.Youcanuseastrongnametoensurethis.Evenifyouusetheassemblieswithinonlyasingleapplication,youcanstrongnamethemtoensurethatyourapplicationusestheircorrectversions.
Strongnamessatisfythefollowingrequirements:Strongnamesguaranteenameuniquenessbyrelyingonuniquekeypairs.Noonecangeneratethesameassemblynamethatyoucanbecauseanassemblygeneratedwithoneprivatekeyhasadifferentnamethananassemblygeneratedwithanotherprivatekey.Strongnamesprotecttheversionlineageofanassembly.Astrongnamecanensurethatnoonecanproduceasubsequentversionofyourassembly.Userscanbesurethataversionoftheassemblytheyareloadingcomesfromthesamepublisherthatcreatedtheversionoriginallyprovidedwiththeapplication.Strongnamesprovideastrongintegritycheck.Passingthe.NETFrameworksecuritychecksguaranteesthatthecontentsoftheassemblyhavenotbeenchangedsinceitwasbuilt.However,notethatstrongnamesalonedonotimplyaleveloftrustsuchasthatprovidedby,forexample,adigitalsignatureandsupportingcertificate.
Forinformationaboutdeployingassembliesintotheglobalassemblycache,seeWorkingwithAssembliesandtheGlobalAssemblyCache.
![Page 191: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/191.jpg)
UsingVisualStudiotoStrongNameEnterpriseLibraryAssembliesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 192: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/192.jpg)
MicrosoftEnterpriseLibrary5.0
UpdatingApplicationBlockAssemblies
IfanupgradedversionofanEnterpriseLibraryApplicationBlockbecomesavailable,youcaninstallthenewversionandhaveallapplicationsusetheupdatedassembly.However,ifthenewversionintroducescompatibilityproblemsforcertainapplications,youcaninstallthenewversionintheglobalassemblycacheandconfiguresomeapplicationstousetheupdatedversion,whileotherscontinuetousetheearlierversion.
![Page 193: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/193.jpg)
UpdatingPrivateAssemblies
![Page 194: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/194.jpg)
UpdatingSharedAssembliesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 195: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/195.jpg)
MicrosoftEnterpriseLibrary5.0
PartialTrustEnvironments
ApplicationsthatuseversionsoftheEnterpriseLibrarypriortoversion3.0requireenoughpermissionssothattheonlysecurityleveltheycanuseisfulltrust.WithlaterversionsofEnterpriseLibrary,includingthisversion,youcanrunapplicationsunderpartialtrust.AcommonexampleisanASP.NETapplicationthatrunsinahostedenvironment.Typically,thesetypesofapplicationsrequireonlyenoughpermissionstorunundermediumtrust.DependingontheEnterpriseLibraryfeaturesthatyourapplicationuses,youmayneedtograntadditionalpermissionsbeyondthosegrantedbyadefaultpartial-trustpolicy.
Thistopiccontainsthefollowingsections:OverviewofPartialTrustEnterpriseLibraryandPartialTrustEnterpriseLibraryCodeAccessSecurityandtheSecurityTransparentAttribute
![Page 196: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/196.jpg)
OverviewofPartialTrust
![Page 197: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/197.jpg)
EnterpriseLibraryandPartialTrust
![Page 198: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/198.jpg)
EnterpriseLibraryCodeAccessSecurityandtheSecurityTransparentAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 199: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/199.jpg)
MicrosoftEnterpriseLibrary5.0
CustomizingtheMediumTrustPolicy
Thetablesinthefollowingsectionsshowtheadditionalpermissions—beyondthosegrantedbydefaultinthemediumtrustpolicy—thatmayberequiredbyyourapplication.Youneedtogranttheseadditionalpermissionsonlyifyouwanttousethesespecificfeatures.Unlessotherwisenoted,makethesemodificationsinthecustompolicyfile.
Forextendedexamplesofhowtomodifyacustompolicyfile,seeHowTo:UseMediumTrustinASP.NET2.0onMSDN.Ifyouareusingapartial-trustpolicyotherthanmediumtrust,otherrestrictionsandpermissionsmayapply.Foratablethatliststhedifferentpermissionsandthetrustpoliciesthatallowthem,seeASP.NETCodeAccessSecurityonMSDN.
Theseadditionalpermissionsarethefollowing:GeneralPermissionsCachingApplicationBlockPermissionsCryptographyApplicationBlockPermissionsDataAccessApplicationBlockPermissionsExceptionHandlingApplicationBlockPermissionsLoggingApplicationBlockPermissionsSecurityApplicationBlockPermissionsPolicyInjectionApplicationBlockPermissionsValidationApplicationBlockPermissions
Thenextsectionsdescribethesepermissions.
![Page 200: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/200.jpg)
GeneralPermissions
![Page 201: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/201.jpg)
CachingApplicationBlock
![Page 202: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/202.jpg)
CryptographyApplicationBlock
![Page 203: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/203.jpg)
DataAccessApplicationBlock
![Page 204: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/204.jpg)
ExceptionHandlingApplicationBlock
![Page 205: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/205.jpg)
LoggingApplicationBlock
![Page 206: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/206.jpg)
SecurityApplicationBlock
![Page 207: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/207.jpg)
PolicyInjectionApplicationBlock
![Page 208: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/208.jpg)
ValidationApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 209: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/209.jpg)
MicrosoftEnterpriseLibrary5.0
LimitationsWhenUsingPartialTrust
TheremaybesomelimitationsregardinghowyouusepartialtrustwithanEnterpriseLibraryapplicationblock.Theselimitationsincludethefollowing:
EnterpriseLibrarythrowsaSecurityExceptionifitcannotobtainthemandatorypermissions.SomecallstoLoggingApplicationBlocktracelistenerclassesfail.ASP.NETapplicationdirectoriesrequirespecificpermissions.TheAzManproviderisnotavailablewithpartialtrust.
![Page 210: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/210.jpg)
EnterpriseLibraryThrowsSecurityException
![Page 211: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/211.jpg)
LimitationsonLoggingApplicationBlockTraceListeners
![Page 212: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/212.jpg)
ASP.NETApplicationDirectoriesRequirePermissions
![Page 213: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/213.jpg)
AzManProviderNotAvailableToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 214: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/214.jpg)
MicrosoftEnterpriseLibrary5.0
AdministeringEnterpriseLibrary
ThistopicdescribessomeofthemainscenariosforsystemadministratorsandoperatorswhomanageapplicationsthatuseEnterpriseLibrary.Ingeneral,theprocessesandtechniquesarenodifferentfromthoseinvolvedinmanagingany.NETapplication.However,EnterpriseLibrarydoesprovideseveralusefulfeaturesdesignedtomakeadministrationandmanagementeasier.Thissectioncoversthefollowingtopics:
RunningMultipleVersionsofEnterpriseLibraryRunTimeConfigurationChangestotheRunTimeEnvironmentInstrumentationwithintheApplicationBlocksIntegrationwithEnterpriseManagementToolsDebuggingUsingtheSourceCode
![Page 215: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/215.jpg)
RunningMultipleVersionsofEnterpriseLibrary
![Page 216: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/216.jpg)
RunTimeConfiguration
![Page 217: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/217.jpg)
ChangestotheRunTimeEnvironment
![Page 218: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/218.jpg)
InstrumentationwithintheApplicationBlocks
![Page 219: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/219.jpg)
IntegrationwithEnterpriseManagementTools
![Page 220: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/220.jpg)
DebuggingUsingtheSourceCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 221: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/221.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingEnterpriseLibrary
EnterpriseLibrarycanserveasthebasisforacustomlibrary.Youcantakeadvantageoftheextensibilitypointsincorporatedineachapplicationblockandextendtheapplicationblockbysupplyingnewproviders.Youcanalsomodifythesourcecodefortheexistingapplicationblockstoincorporatenewfunctionality.UsetheguidelinesinthistopicwhenyouextendtheEnterpriseLibrary.
TherearethreewaystoextendtheEnterpriseLibrary.Youcan:Writecustomproviders.Fordetailedinformationaboutcreatingprovidersandextensionsforeachapplicationblock,seethe"ExtendingandModifying"topicinthesectionsofthisdocumentationforeachoftheblocks.Forgeneralinformationaboutcreatingcustomproviders,andintegratingwiththeconfigurationtools,seeCreatingCustomProvidersforEnterpriseLibrary.Modifythesourcecodeofanapplicationblock.Formoreinformationaboutthedesignofeachblock,seethetopic"DesignoftheApplicationBlock"inthesectionsofthisguidancedevotedtoeachoftheapplicationblocks.Writeanewapplicationblock.Youcanusetheexistingblocksasguidancetocreateacompletelynewblock.YouwillalsofindadditionalinformationandresourcesoncreatingandextendingtheblocksontheEnterpriseLibrarycommunitycontributionssiteathttp://www.codeplex.com/entlibcontrib/.
ThefollowingsectionsexplainsomeofthefactorstokeepinmindwhenextendingormodifyingEnterpriseLibrary.
![Page 222: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/222.jpg)
GuidelinesforExtendingEnterpriseLibrary
![Page 223: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/223.jpg)
GuidelinesforModifyingtheApplicationBlocksToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 224: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/224.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingCustomProvidersforEnterpriseLibrary
EnterpriseLibraryincorporatesaneasy-to-useextensiblemechanismforyoutoaddyourowncustomprovidersifyourequirespecializedbehavior.YoucanplugincustomprovidersthatyoucreatewithoutneedingtorecompileEnterpriseLibrary.
Inaddition,theconfigurationmechanismmakesiteasytoaddafulldesign-timeexperiencetoyourcustomproviderssothattheycanbeconfiguredwithintheconfigurationtoolsinexactlythesamewayasthebuilt-inproviders.Theconfigurationtoolsaremetadatadriven,andreadinformationaboutavailableprovidersandextensionsfromassemblieslocatedintheirrun-timefolderonstartup.Thismeansthatyoudonotneedtorecompiletheconfigurationtooltoaddadesign-timeexperienceforyourcustomproviders.
ThefollowingtopicsdescribethegeneralprocessforcreatingacustomproviderforEnterpriseLibrary,andincludeanexampleofasimpleprovider:
EnterpriseLibraryExtensionPoints.ThistopicliststheextensionpointsforEnterpriseLibrary,andtheclassesyoucanusewhencreatingacustomproviderandspecifyingconfigurationinformationforit.EnterpriseLibraryConfigurationIntegration.ThistopicdescribesthetwowaysthatyoucanintegratecustomprovidersintotheEnterpriseLibraryconfigurationsystem.CreatingaCustomProvider.ThistopicprovidestheinformationrequiredforcreatingaproviderthatyouaddtotheapplicationconfigurationusingtheAddCustom[providertype]menucommandsintheconfigurationtools,andexplainshowyoucancreateafullyintegrateddesign-timeexperienceforacustomprovider.
YoucandownloadaVisualStudioprojectcontainingtheexampleproviderdescribedinthissection.Theprojectincludesacustomexceptionhandlerinbothbasicandfullconfigurationintegrationmodes,andasimpleconsoleapplicationthatusesbothversionsofthehandler.Todownloadthesample,gotohttp://www.codeplex.com/entlib/.
Note:
![Page 225: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/225.jpg)
ThissectiondoesnotcoverextendingtheUnitydependencyinjectionandinterceptionmechanism.ForinformationabouthowyoucanextendUnity,seethedocumentationavailableontheUnityWebsiteathttp://www.codeplex.com/unity/.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 226: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/226.jpg)
MicrosoftEnterpriseLibrary5.0
EnterpriseLibraryExtensionPoints
ThefollowingtableslisttheextensionpointsthatEnterpriseLibraryprovidesforeachoftheapplicationblocks.Foreachtypeofproviderorextension,thetablesshow:
Theinterfaceyoucanimplementand/orthebaseclassyoucaninherit.Thetypeoftheconfigurationelementtoapplytoyourcustomclasstoenablebasicintegrationwiththeconfigurationsystem.Thebaseclassthatyoumustinheritinyourcustomconfigurationelementifyouwanttoimplementfulldesign-timeconfigurationintegration.Yourcustomproviderorextensionwillthenuseyourcustomconfigurationelementclassasitsconfigurationelementtype,insteadofthedefaultshownintheConfigurationElement(basicintegration)column.
ProvidersandextensionsthatcannotbeintegratedwiththeconfigurationtoolshavenoentryintheConfigurationElement(basicintegration)column.
![Page 227: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/227.jpg)
CachingApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
BackingStore
IBackingStoreBaseBackingStore
CustomCacheStorageData CacheStorageData
CacheManager
ICacheManager CustomCacheManagerData CacheManagerDataBase
ExpirationPolicy
ICacheItemExpiration n/a n/a
StorageEncryptionProvider
IStorageEncryptionProvider n/a StorageEncryptionProviderData
![Page 228: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/228.jpg)
CryptographyApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
HashAlgorithmProvider
IHashProvider CustomHashProviderData
SymmetricEncryptionAlgorithmProvider
ISymmetricCryptoProvider CustomSymmetricCryptoProviderData
![Page 229: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/229.jpg)
DataAccessApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
DatabaseProvider
Database n/a n/a
![Page 230: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/230.jpg)
ExceptionHandlingApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
ExceptionHandler
IExceptionHandler CustomHandlerData ExceptionHandlerData
ExceptionFormatter
ExceptionFormatter n/a n/a
![Page 231: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/231.jpg)
LoggingApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
LogEntryFormatter
ILogFormatter CustomFormatterData FormatterData
TraceListener
CustomTraceListener CustomTraceListenerData TraceListenerData
LogFilter ILogFilterLogFilter
CustomLogFilterData LogFilterData
IfyouimplementacustomLogFilterbyimplementingtheILogFilterinterfaceorbyextendingtheLogFilterbaseclass,youmustbeawareofanissuethatcanpreventapplicationcodefromresolvingtheconfigurednameoftheprovider.However,thisisonlyanissuewhenyouwishtoquerythecollectionoffilterswhencheckingifalogentrywillbespecificallyblockedbythisfilter.TheILogFilterinterfacedefinesaNamepropertythatshouldreturnthenameoftheinstanceofthecustomlogfilterfromtheconfiguration.However,therecurrentlyisnowaytoretrievethatnamefromwithinyourcustomlogfilter.Instead,youcanpassakey/valuepairintheNameValueCollectionreceivedbytheconstructor,andusethistosettheNamepropertyofthefilter.Whenconfiguringyourcustomlogfilter,youwillhavetoduplicatethename:oncefortheactualnameofthatinstanceofthecustomlogfilter,andagaininthenamedpropertycollectionthatispassedtotheconstructor.
![Page 232: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/232.jpg)
PolicyInjectionApplicationBlockPolicyinjectionisafeaturedrivenbytheUnityinterceptionmechanism.Youcancreatecustombehaviors,callhandlers,callhandlerattributes,andmatchingrulesforusewiththeUnityinterceptionmechanism.Formoreinformation,seehttp://www.codeplex.com/unity/.
![Page 233: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/233.jpg)
SecurityApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
AuthorizationProvider
AuthorizationProvider CustomAuthorizationProviderData AuthorizationProviderData
SecurityCacheProvider
ISecurityCacheProvider CustomSecurityCacheProviderData SecurityCacheProviderData
![Page 234: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/234.jpg)
ValidationApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
Validator Validator<T>Validator
CustomValidatorData ValidatorData
ValidatorAttribute
ValueValidatorAttribute n/a n/a
FormoreinformationaboutcreatingcustomprovidersandextensionsforEnterpriseLibrary,seeEnterpriseLibraryConfigurationIntegrationandCreatingaCustomProvider.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 235: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/235.jpg)
MicrosoftEnterpriseLibrary5.0
EnterpriseLibraryConfigurationIntegration
EnterpriseLibraryallowsyoutoeasilyintegratecustomprovidersandextensionsintothelibraryinsuchawaythatyoucanconfigurethemusingtheEnterpriseLibraryconfigurationtools.Therearetwotypes,orlevels,ofconfigurationintegration.
![Page 236: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/236.jpg)
BasicConfigurationIntegration
![Page 237: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/237.jpg)
FullConfigurationIntegrationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 238: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/238.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingaCustomProvider
Thefollowingstepsdescribetheprocessforcreatingacustomprovider:PreparingYourProjectImplementingtheInterfaceorExtendingtheBaseClassSpecifyingtheConfigurationElementTypeAddingFullDesign-timeIntegrationSummaryofSteps
![Page 239: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/239.jpg)
PreparingYourProject
![Page 240: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/240.jpg)
ImplementingtheInterfaceorExtendingtheBaseClass
![Page 241: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/241.jpg)
SpecifyingtheConfigurationElementType
![Page 242: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/242.jpg)
AddingFullDesign-timeIntegration
![Page 243: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/243.jpg)
SummaryofStepsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 244: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/244.jpg)
MicrosoftEnterpriseLibrary5.0
DesignofEnterpriseLibrary
EnterpriseLibraryincorporatesasetofbestpracticesinitsoveralldesign.Amongthesearethefollowing:
Itusescommonapplicationblockfunctionality(theEnterpriseLibraryCore).Itusesuniformconventionsfornamingandversioning.Itincorporatesinstrumentationintoallapplicationblocks.Itusesunittestswrittenduringthedesignphase.
ThesectiondescribesthedesignofEnterpriseLibraryandincludesthefollowingtopics:
DesignPatterns.ThistopicdescribestheuseofdesignpatternswithinEnterpriseLibrary.TheEnterpriseLibraryCore.ThistopicdescribestheEnterpriseLibraryCore,includingtheconfigurationsystem.Providers.Thistopicdescribestheuseofproviderstoimplementextensibility.DesignTimeConfiguration.Thistopicdescribesthedesign-timeconfigurationfeaturesofEnterpriseLibrary.TheDependencyInjectionModel.ThistopicdescribesthedependencyinjectionmechanismusedbyEnterpriseLibrarytoinstantiateobjectsandmanagetheirlifetimes.Instrumentation.ThistopicdescribestheimplementationofinstrumentationwithinEnterpriseLibrary.GroupPolicySupport.ThistopicdescribesGroupPolicysupportusingtheManageableConfigurationSource.UnitTests.ThistopicdescribestheuseofunittestswithinEnterpriseLibrary.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 245: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/245.jpg)
MicrosoftEnterpriseLibrary5.0
DesignPatterns
Insoftwarearchitectureanddevelopment,apatternisadescriptionofarecurringproblemthatoccursinaspecificcontextand,basedonasetofguidingforces,suggestsasolution.Thesolutionisusuallyasimplemechanismbecauseitisacollaborationbetweentwoormoreclasses,objects,services,processes,threads,components,ornodesthatworktogethertosolvetheunderlyingarchitectureordevelopmentchallenge.
Patternsareusefultodevelopersandarchitectsbecausetheydothefollowing:Theydocumentsimplemechanismsthatwork.Theyprovideacommonvocabularyandtaxonomyfordevelopersandarchitects.Theyallowsolutionstobedescribedconciselyascombinationsofpatterns.Theyenablereuseofarchitecture,design,andimplementationdecisions.
TheEnterpriseLibraryapplicationblocksusethefollowingpatterns(amongothers):
Plug-inpattern.Thispatternextendsthebehaviorofaclassbyallowingextensionstoplugintoanabstractclassthat,inturn,plugsintoacoreclass.Thiscreatesanewsubclassthatincludesonlythecapabilitiesrequiredinthespecificcontext.DependencyInjectionpattern.Withthispattern,youcaninjectobjectsintoaclass,insteadofrelyingontheclasstocreatetheobject.
Formoreinformationaboutpatterns,seetheMicrosoftpatterns&practicesWebsite.
![Page 246: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/246.jpg)
Plug-inPattern
![Page 247: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/247.jpg)
DependencyInjectionPatternToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 248: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/248.jpg)
MicrosoftEnterpriseLibrary5.0
TheEnterpriseLibraryCore
ManytasksthattheEnterpriseLibraryapplicationblocksperformarecommonacrossmorethanoneapplicationblockandarealsousefulinapplicationcodeoutsideofEnterpriseLibrary.Examplesareroutinesthatserializedataoraccessconfigurationinformation.Topromoteusability,theseroutinesresideinacommonassemblynamedtheEnterpriseLibraryCore.
Inaddition,alltheapplicationblocksaredesignedtohavealimitednumberofdependenciessothattheycanbeusedindividuallyaswellaswithotherapplicationblocks.AllapplicationblocksexceptUnitydependontheEnterpriseLibraryCore,whichisalogicalgroupingmadeupofthefollowingsubsystems:
TheCommonassemblyInstrumentationfortheapplicationblocksConfigurationhelperclassesanddesign-timeconfigurationcomponents
ForinformationaboutthedependenciesbetweenapplicationblocksandtheEnterpriseLibraryCore,seeDependenciesinEnterpriseLibrary.
![Page 249: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/249.jpg)
TheCommonAssembly
![Page 250: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/250.jpg)
Instrumentation
![Page 251: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/251.jpg)
ConfigurationHelperClassesandDesign-timeComponentsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 252: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/252.jpg)
MicrosoftEnterpriseLibrary5.0
Providers
AproviderintheMicrosoft.NETFrameworkisanintermediarypieceofcode;withit,yourapplicationcanconnecttoaserviceordatasourceandthenretrieveormodifyanobjectordatafromthatserviceorsource.TheEnterpriseLibraryincludesmanyproviders.Inaddition,youcancreateyourownprovidertosupplyinformationthatyouneedforyourspecificapplication.
Aprovidertypedefinesaninterfacethatisassociatedwithacapabilityanapplicationblockmusthavetoperformcorrectly.Aproviderisaspecificimplementationofaprovidertype.Eachapplicationblockincludesoneormoreprovidersforeachprovidertype.Youcanalsowritecustomprovidersforapplicationblocks.Separatingtheapplicationblock'sfunctionalityfromspecificimplementationsofitscapabilitiesachievesthefollowinggoals:
Variability.Thisallowsyoutochoosefrommultipleimplementationsofthesamecapability,accordingtotherequirementsofaspecificapplication.Extensibility.Thisallowsyoutousetheapplicationblockinenvironmentswherethecapabilityinquestionhasamandatoryimplementation.Forexample,anapplicationcanrequireaspecificencryptionalgorithmwhendeployedtoaparticularenvironment.Encapsulation.Thisallowsyoutoreacttochangesintheenvironmentinwhichtheapplicationblockisused.Withproviders,functionalitythatisnotapartoftheapplicationblock'scorefunctionalitycanbereplacedorupgradedwithoutaffectingotherareasoftheapplicationblock.Portabilityacrossenvironments.Thisallowsyoutodeploytheapplicationblockinanewenvironmentwithprovidersspecifictothatenvironment.Youcanalsocreateprovidersthatruninoneenvironmentandsimulatebehaviorfromadifferentenvironment.Minimizedcouplingbetweenapplicationblocks.Applicationblocksthataredependentonotherapplicationblockscanencapsulatethisdependencyinaprovider.Thismeansthattheapplicationblockislessvulnerabletorevisionsintheapplicationblockonwhichitdepends.Forexample,theExceptionHandlingApplicationBlockincludestheloggingexceptionhandler.ThishandlerisdependentontheLoggingApplicationBlockandisincludedasaprovider.AnewversionoftheLogging
![Page 253: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/253.jpg)
ApplicationBlockwouldrequireonlyanewlogginghandlerprovider;therestoftheExceptionHandlingApplicationBlockcanremainunchanged.
Forinformationaboutcreatingyourownprovidersfortheapplicationblocks,seethe"ExtendingandModifying"sectionofthedocumentationforeachapplicationblock.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 254: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/254.jpg)
MicrosoftEnterpriseLibrary5.0
DesignTimeConfiguration
Allapplicationblocksincludebothrun-timesupportanddesign-timesupportforconfigurationsettings.Therun-timesupportincludesclassesthatrepresenttheconfigurationsettings.TheConfigurationApplicationBlockusestheseclassdefinitionswhenitloadsconfigurationsettings.Itreadstheconfigurationsettingsfromstorageandreturnsobjectsthatcontaintheconfigurationdatatotheapplicationblock.
Thedesign-timeconfigurationsupportincludesclassesthatallowyoutochangetheconfigurationsettingsbyusingtheEnterpriseLibraryconfigurationtools.Theseclassesdefineavisualrepresentationofthedifferentconfigurationsettings,specifytheactionsthatcanbeperformedbasedonthecurrentconfigurationstate,andprovidetheabilitytovalidatetheconfigurationsettings.
Thefollowingfigureillustratestherelationshipbetweentherun-timeconfigurationsupportandthedesign-timeconfigurationsupport.
Thedesign-timeclassesdependontheconfigurationrun-timeclassesbecause
![Page 255: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/255.jpg)
theyobtainthecurrentconfigurationsettingsfromtheconfigurationrun-timeobjects.Whenyouchangethesesettingsandsavethechanges,thedesign-timeobjectsupdatetherun-timeobjects,whicharethensavedinstorage.However,therun-timeclasseshavenodependencyonthedesign-timeclasses.Thereisasinglelightweightdesign-timeassemblythatcontainsdesign-timecoreandsomeblock-specificclasses.Thisisseparatefromtheassembliescontainingtherun-timeimplementations.Thedesign-timeassemblyisnotrequiredforrunninganapplicationthatusestheapplicationblocks.However,itisrequiredwhenyouusetheconfigurationconsoletochangetheconfigurationofanapplicationblock.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 256: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/256.jpg)
MicrosoftEnterpriseLibrary5.0
TheDependencyInjectionModel
ThistopicdescribesthemechanismusedbyEnterpriseLibrarytocreateandmanagethelifetimeofobjectswithinthecoreandtheapplicationblocks.EnterpriseLibraryusesadependencyinjectionmechanismtocreateandmanagethelifetimeofalltheEnterpriseLibraryobjectsitcreates.Dependingonthestyleofyourapplication,itmayusethesamedependencyinjectioncontainerthatEnterpriseLibraryuses.Thistopiccontainsthefollowingsections:
ApplicationandContainerInitializationUsinganAlternativeDependencyInjectionContainerMoreInformation
TolearnhowtousetheUnitydependencyinjectionapproachwhenwritingapplicationcode,seeUsingEnterpriseLibraryinApplications.
![Page 258: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/258.jpg)
UsinganAlternativeDependencyInjectionContainer
![Page 259: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/259.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 260: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/260.jpg)
MicrosoftEnterpriseLibrary5.0
Instrumentation
InEnterpriseLibrary,theinterfacesandclassesresponsibleforloggingeventstotheWindowsEventLogorupdatingWindowsPerformanceCountersareseparatedfromthosethatindicateaninstrumentation-worthyactivityhasoccurred.
EachapplicationblockcontainsoneormoreclassesresponsiblefortranslatingactivitiesfromwithintheblockintoEventLogmessagesorPerformanceCounterupdates.Theseclassesaregenerallyknownasinstrumentationprovidersbecausetheyprovideinstrumentationserviceswithinthatblock.Classeswithinanapplicationblockusetheinstrumentationproviderstoindicatethatanactivityhasoccurred.
Eachblockisresponsibleforadifferentsetofactivitiesandsotheexactinterfaceoftheprovidervariesforeachblock.Forexample,theinstrumentationproviderinterfacefortheCachingInstrumentationProviderclassisasfollows:C#
publicinterfaceICachingInstrumentationProvider
{
voidFireCacheUpdated(longupdatedEntriesCount,longtotalEntriesCount);
voidFireCacheAccessed(stringkey,boolhit);
voidFireCacheExpired(longitemsExpired);
voidFireCacheScavenged(longitemsScavenged);
voidFireCacheCallbackFailed(stringkey,Exceptionexception);
voidFireCacheFailed(stringerrorMessage,Exceptionexception);
}
TheCacheclassintheCachingBlockusesanICachingInstrumentationProvidereachtimeitmustindicatethecachewasaccessed.WhenthecacheisaccesseditcallstheFireCacheAccessedmethodoftheinstrumentationprovider.
Theinstrumentationprovidersaretypicallyconnectedtootherclasseswithin
![Page 261: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/261.jpg)
theblockthroughaconstructorparameter.TheCacheclass,forexample,takesanICachingInstrumentationProviderasshownhere.C#
publicclassCache:ICacheOperations,IDisposable
{
publicCache(IBackingStorebackingStore,
ICachingInstrumentationProviderinstrumentationProvider)
{
...
}
...
}
Becausetheimplementationsfortheinstrumentationproviderinterfacesareregisteredwithinthedependencyinjectioncontainer,theyareinjectedintotheclassesthatrequirethem.
![Page 262: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/262.jpg)
HowInstrumentationProvidersWorkToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 263: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/263.jpg)
MicrosoftEnterpriseLibrary5.0
GroupPolicySupport
ThisreferencesupplementstheinformationinUsingGroupPolicywithEnterpriseLibrary.Itisdividedintothefollowingsections:
TheManageableConfigurationSourceClass.ThissectiondescribesthedesignoftheclassthatprovidesGroupPolicyconfigurationsupportinEnterpriseLibrary.IntegrationofGroupPolicywithEnterpriseLibraryApplications.ThissectionprovidesinformationabouthowinstancesoftheManageableConfigurationSourceareintegratedwithGroupPolicyandincludesinformationaboutGroupPolicytemplatestructure.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 264: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/264.jpg)
MicrosoftEnterpriseLibrary5.0
TheManageableConfigurationSourceClass
ThistopicdescribestheclassesthatmakeuptheManageableConfigurationSourceclass.
![Page 265: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/265.jpg)
ManageableConfigurationSource
![Page 266: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/266.jpg)
ManageabilityHelperToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 267: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/267.jpg)
MicrosoftEnterpriseLibrary5.0
IntegrationofGroupPolicywithEnterpriseLibraryApplications
TheManageableConfigurationSourceclassreadsconfigurationoverridesfromtheregistryandappliesthoseoverridestoanapplicationconfigurationfile.Byreadingtheregistryinthisway,thisconfigurationsourceallowsyoutouseGroupPolicytospecifythesettings.AGroupPolicytemplatedefinestheconfigurationoptionsforeachapplicationthatisconfiguredinGroupPolicyanddefinesthedefaultoptionsinGroupPolicyforeachconfigurationoption.OneGroupPolicytemplateisrequiredforeachapplicationbecauseaseparateregistrykeyrepresentseachapplication.Thekeyisbasedontheapplicationname.
TosimplifythecreationofGroupPolicytemplates,youcanusetheAdministrativeTemplateGeneratorclasstogenerateanAdmContentobject,andthenwritethiscontenttoastreaminordertogenerateADMfilesfromtheEnterpriseLibraryconfigurationtools.Thesetemplatesusethesettingsdefinedintheapplicationconfigurationfiletodeterminethedefaultsettingsforeachoption.TheyalsodeterminethestructureoftheADMtemplate,whichmustmatchthecontentsoftheconfigurationfile.
InthisversionofEnterpriseLibrary,templatesandGroupPolicysupportareavailableforalltheapplicationblocks,exceptfortheValidationApplicationBlock,thePolicyInjectionApplicationBlock,andUnity.GroupPolicyisafairlystaticandflatmechanism,andtheconfigurationfortheseapplicationblocksisquitedynamicandusuallycomplex.Therefore,itwouldbealmostimpossibletoprovideauseableuserinterfaceimplementationfortheseapplicationblocks.
Note:ApplicationsthatuseGroupPolicytospecifytheirsettingsmustdefineanduseaManageableConfigurationSourceintheconfigurationsourcessection,andsettheEnableGroupPolicyflagonthatsourcetotrue.Youcanusetheconfigurationtoolstoconfigurethissetting.
Thissectioncontainsthefollowingtopics:
![Page 268: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/268.jpg)
GroupPolicyTemplateStructureGeneralSettingsfortheApplicationBlocksExceptionstotheGeneralTemplateStructureApplyingGroupPolicySettingsLimitationsofGroupPolicySupport
![Page 270: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/270.jpg)
GeneralSettingsfortheApplicationBlocks
![Page 271: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/271.jpg)
ExceptionstotheGeneralTemplateStructure
![Page 272: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/272.jpg)
ApplyingGroupPolicySettings
![Page 273: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/273.jpg)
LimitationsofGroupPolicySupportToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 274: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/274.jpg)
MicrosoftEnterpriseLibrary5.0
UnitTests
EnterpriseLibraryincludesVisualStudio®solutionfilesthatincludeVisualStudioTeamSystemunittestswiththeapplicationblockprojects.YoucanusethemainEnterpriseLibrarysolutionfile(EnterpriseLibrary.VSTS.sln)tobuildtheentireEnterpriseLibrarywiththeunittests.ThissolutioncontainstheentiresetofapplicationblockprojectsandtheEnterpriseLibrarycoreprojects,andincludesallunittestsforexecutionwiththeVisualStudioTeamSystem.
TheEnterpriseLibrarysolutionfilesincludetwobuildconfigurations:ReleaseandDebug.Allprojectswithinasolutionfilearecompiledinbothconfigurations,includingtheunittestprojects.Formoreinformation,seeBuildingEnterpriseLibraryfromtheSourceCode.
Note:ThisreleaseofEnterpriseLibrarydoesnotincludesolutionsthatusetheNUnittestframework.
![Page 275: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/275.jpg)
SoftwareRequirements
![Page 277: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/277.jpg)
UsingtheUnitTestsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 278: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/278.jpg)
MicrosoftEnterpriseLibrary5.0
TheCachingApplicationBlock
TheEnterpriseLibraryCachingApplicationBlockletsdevelopersincorporatealocalcacheintheirapplications.Itsupportsbothanin-memorycacheand,optionally,abackingstorethatcaneitherbethedatabasestoreorisolatedstorage.TheCachingApplicationBlockcanbeusedwithoutmodification;itprovidesallthefunctionalityneededtoretrieve,add,andremovecacheddata.Configurableexpirationandscavengingpoliciesarealsopartoftheblock.
Note:CachingApplicationBlockfunctionalityisbuiltinto.NETFramework4.0;thereforetheEnterpriseLibraryCachingApplicationBlockwillbedeprecatedinreleasesafter5.0.Youshouldconsiderusingthe.NET4.0System.Runtime.CachingclassesinsteadoftheCachingApplicationBlockinfuturedevelopment.
TheEnterpriseLibraryCachingApplicationBlockincludesthefollowingfeatures:
YoucanusethegraphicalEnterpriseLibraryconfigurationtoolstomanageconfigurationsettings.Youcanconfigureapersistentstoragelocation,usingeitherisolatedstorageortheEnterpriseLibraryDataAccessApplicationBlock,whosestateissynchronizedwiththein-memorycache.AdministratorscanmanagetheconfigurationusingGroupPolicytools.Youcanextendtheblockbycreatingcustomexpirationpoliciesandstoragelocations.Youareassuredthattheblockperformsinathread-safemanner.
ThissectionincludesthefollowingtopicsthatwillhelpyoutounderstandandusetheCachingApplicationBlock:
WhatDoestheCachingApplicationBlockDo?Thistopicprovidesabriefoverviewthatwillhelpyoutounderstandwhattheblockcando,andexplainssomeoftheconceptsandfeaturesitincorporates.Italsoprovidesasimpleexampleofthewaythatyoucanwritecodetousethe
![Page 279: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/279.jpg)
block.WhenShouldIUsetheCachingApplicationBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andanyalternativetechniquesyoumayconsider.Italsoprovidesdetailsofanylimitationsoftheblockthatmayaffectyourdecisiontouseit.DevelopingApplicationsUsingtheCachingApplicationBlock.ThistopicfirstexplainshowtoconfiguretheCachingApplicationBlockandaddittoyourapplication.Itthenexplainshowtoselectabackingstore.KeyScenarios.Thissectiondemonstrateshowtousetheblocktoperformtypicalcachingoperations.DesignoftheCachingApplicationBlock.ThistopicexplainsthedecisionsthatwentintodesigningtheCachingApplicationBlockandtherationalebehindthosedecisions.ExtendingandModifyingtheCachingApplicationBlock.Thistopicexplainshowtoextendtheblockbyaddingyourownbackingstoreandyourownexpirationpolicies.Italsoexplainshowtomodifyitbychangingthesourcecode.DeploymentandOperations.ThistopicexplainshowtodeployandupdatetheCachingApplicationBlockassemblies.
![Page 280: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/280.jpg)
MoreInformationForrelatedinformation,seethefollowingpatterns&practicesguidesanddocuments:
MicrosoftApplicationArchitectureGuide,2ndEditionCachingArchitectureGuidefor.NETFrameworkApplicationsEnterpriseLibraryhomepageonMSDN®EnterpriseLibraryontheCodePlexWebsite
Forlinkstoexternalcachingproviders,seethe"MoreInformation"sectioninTheCachingApplicationBlockonMSDN.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 281: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/281.jpg)
MicrosoftEnterpriseLibrary5.0
WhatDoestheCachingApplicationBlockDo?
TheCachingApplicationBlockprovidesanin-memorycachethatyourapplicationcanmanipulatethroughasimpleAPItostoreandretrieveitems,andtoobtaininformationaboutthestoreditems.Inaddition,youcanconfigureapersistentorcustombackingstoreforyourcache,and—ifrequired—encrypttheinformationstoredthere.Youcanconfiguremorethanonecacheforyourapplication,andspecifyapartitionforeachonesothatdatafrommultiplecachescanbestoredinseparatecontainerswithinthesamebackingstorelocation,suchasadatabase.ThefollowingschematicshowsthemainelementsoftheCachingApplicationBlock.
Atapplicationstartup,theblockloadsthein-memorycachefromthebackingstore(ifconfigured).Alternatively,youcanalsoloadthecacheyourselfifyouwanttoimplementadelayedloadingpattern.Astheapplicationruns,theblockcheckstheexpirationofcacheditemsandremovesthemfromthecache.Expirycanbeconfiguredbasedonslidingorabsolutetimevalues;orthroughdependenciesonfiles,othercacheditems,orexternalresources.Theblockalsomanagesthecacheinconjunctionwithmemoryavailability,basedoncacheditempriorities.
![Page 282: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/282.jpg)
Note:Forinformationaboutthetypesofexpirationyoucanuse,andthedefaultexpirationfornewitems,seeDesignoftheExpirationProcess.
AsapplicationcodeinteractswiththeCacheManager,itupdatesthein-memorycacheand—ifabackingstoreisconfigured—updatesthebackingstore.Youcanconfigureanencryptionproviderforthebackingstore,whichisimplementedbytheCryptographyApplicationBlock,toencrypttheitemsthatarecachedinthebackingstore(notethattheblockdoesnotencryptitemsstoredinthein-memorycache).
TheblockincludesprovidersthatstoredatainadatabaseorinIsolatedStorageonthelocalmachine.Itdoesnotprovideadistributedcachingmechanism.Additionalproviders,includingprovidersthatsupportdistributedcaching,maybeavailablefromthirdpartiesandtheEnterpriseLibrarycommunityWebsite.Formoreinformation,seetheCodePlexCommunityandEnterpriseLibraryContributionsWebsites.
![Page 283: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/283.jpg)
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 284: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/284.jpg)
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheCachingApplicationBlock?
TheCachingApplicationBlockissuitableifyouencounteranyofthefollowingsituations:
Youmustrepeatedlyaccessstaticdataordatathatrarelychanges.Dataaccessisexpensiveintermsofcreation,access,ortransportation.Datamustalwaysbeavailable,evenwhenthesource,suchasaserver,isnotavailable.
YoucanusetheCachingApplicationBlockwithanyofthefollowingapplicationtypes:
WindowsFormsWindowsPresentationFoundation(WPF)WindowsCommunicationFoundation(WCF)ConsoleapplicationWindowsserviceASP.NETWebapplicationorWebserviceifyouneedfeaturesnotincludedintheASP.NETcache
![Page 285: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/285.jpg)
ScenariosfortheCachingApplicationBlock
![Page 286: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/286.jpg)
BenefitsoftheCachingApplicationBlock
![Page 287: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/287.jpg)
LimitationsoftheCachingApplicationBlock
![Page 289: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/289.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 290: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/290.jpg)
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheCachingApplicationBlock
ThissectiondescribeshowtousetheCachingApplicationBlocktodevelopapplications.Itexplainshowtoenterconfigurationinformationfortheblock,incorporateitintoyoursolution,andselectabackingstore.Thissectionincludesthefollowingtopics:
EnteringConfigurationInformationAddingApplicationCodeSelectingaBackingStore
Allblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompileit.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 291: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/291.jpg)
MicrosoftEnterpriseLibrary5.0
EnteringConfigurationInformation
TheseproceduresexplainhowtoconfiguretheCachingApplicationBlock.IfyouaddaDatabaseCacheStorageprovidertotheconfigurationoftheCachingApplicationBlock,theconfigurationtoolautomaticallyaddstheDataAccessApplicationBlock.YoumustconfigurethatblockbeforeyouconfiguretheDatabaseCacheStorageproviderintheCachingApplicationBlockconfiguration.
FordetailsoftheschemafortheCachingApplicationBlockconfiguration,seeSourceSchemafortheCachingApplicationBlock.Youcanalsoconfiguretheblockincodebyusinganalternateconfigurationsource.Formoreinformation,seeAdvancedConfigurationScenariosandUsingtheFluentConfigurationAPI.
ToaddtheCachingApplicationBlock1. Opentheconfigurationfile.Formoreinformation,seeConfiguring
EnterpriseLibrary.2. OpentheBlocksmenuandthenclickAddCachingSettings.3. TheconfigurationtoolautomaticallyaddstheCachingSettingssection
withdefaultvalues,andadefaultCacheManageritem.
Toconfigurecachemanagers1. ClickthepropertiesexpanderarrowintheCachingSettingssectionto
openthelistofproperties.2. (Optional)ChangetheDefaultCacheManagerpropertyname.The
defaultcachemanagerisusedifthecodedoesnotspecifyacachemanager.Eitherenteranewnameorselectonefromthedrop-downlist.ThedefaultnameisCacheManager.
3. (Optional)Ifyouwanttoencrypttheconfiguration,makeaselectionfromtheProtectionProviderdrop-downlist.YoucanselecttheRsaProtectedConfigurationProviderortheDataProtectedConfigurationProvider.SeeEncryptingConfigurationDataforinformationabouttherestrictionsonusingtheRsaProtectedConfigurationProvider.
4. (Optional)Ifyouwanttorunyourapplicationinpartialtrustmode,changetheRequirePermissionpropertytoFalse.ThedefaultisTrue.
5. ToaccessthedefaultCacheManagerproperties,clickthesection
![Page 292: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/292.jpg)
expanderarrowtotheleftofthedefaultCacheManagertitle.Ifyourenamedthecachemanager,thetitlewillbethenameyouassignedit.
6. (Optional)RenametheCacheManagernode.ThedefaultnameisCacheManager.
7. (Optional)SettheBackingStoreproperty.Thedefaultis<none>whichmeansthatthecachemanageronlystoresdatainmemory.Thedrop-downlistshowsyoutheavailablebackingstoresyoucanchoosefrom.YoucanaddbackingstoresintheBackingStorespane.
8. (Optional)SettheNumbertoRemovewhenScavengingproperty.Thisisthenumberofelementstoremoveafterscavengingbegins.Thedefaultsettingis10elements.
9. (Optional)SettheMax.ElementsinCacheBeforeScavengingproperty.Thisisthemaximumnumberofelementsthatcanbeinthecachebeforescavenging.Thedefaultsettingis1000elements.
10. (Optional)SettheExpirationPollingFrequencyproperty.Thisisthefrequencyofthetimerthatregulateshowoftenthebackgroundschedulerchecksforexpireditems.Theunitisseconds,andthedefaultsettingis60.
Bydefault,thecachestoresitemsonlyinmemoryandassignsthevalueofthe
![Page 293: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/293.jpg)
backingstoretoNullBackingStore.YoucanaddcachingstoresandthenconfiguretheCachingApplicationBlocktouseanyofthestoresyouhaveadded.YoucanconfiguretheCachingApplicationBlocktousedatabasecachestorage,isolatedstorage,orcustomcachestorage.DatabasecachestorageusestheDataAccessApplicationBlock.
ToadddatabasecachestorageandconfiguretheCachingApplicationBlocktouseit
1. ClicktheplussigniconintheBackingStorespane,pointtoAddBackingStoresandclickAddDataCacheStorage.
2. TheconfigurationtoolautomaticallyaddstheDatabaseSettingssection.Forinformationaboutconfiguringthissection,seeTheDataAccessApplicationBlockdocumentation.
3. ClickthepropertiesexpanderarrowinthenewDataCacheStoragesectiontoopenthelistofproperties.
4. (Optional)SettheNamepropertybyrenamingtheDataCacheStoragenode.
5. SettheDatabaseInstancepropertybymakingaselectionfromthetextboxdrop-downlist.Thisisthenameofthedatabaseconnectionstring.ItmustcorrespondtothenameofaconnectionstringintheDatabaseSettingssection.
6. Ifyouwanttoencrypttheinformationstoredinthedatabase,youmusthaveconfiguredanencryptionprovider.Toaddanewencryption
![Page 294: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/294.jpg)
provider,clicktheplussigniconintheEncryptionProviderspaneoftheCachingSettingssection,pointtoAddEncryptionProvidersandthenclickAddSymmetricCryptoProvider(thisistheonlyencryptionprovideroffered).TheconfigurationtoolautomaticallyaddstheCryptographySettingssection.
7. IntheCryptographySettingssection(nottheCachingSettingssection),addasymmetriccryptographyprovidertotheconfiguration.Forinformationaboutconfiguringthisblock,seeTheCryptographyApplicationBlockdocumentation.
8. IntheCachingSettingssection,selectthenewsymmetricencryptionprovideryouconfiguredintheCryptographySettingssectionoranexistingencryptionproviderinthatsection,inthedrop-downlistfortheSymmetricCryptoProviderproperty.
9. IntheBackingStorespane,intheDataCacheStoragesection,settheEncryptionProviderpropertybyselectingtheSymmetricCryptoProvideritemyoujustconfigured.
10. IntheCacheManagerssection,selectthenewbackingstoreyouaddedinthedrop-downlistfortheBackingStorepropertyofthecachemanagerthatwillusethisbackingstore.
ToaddisolatedstorageandconfiguretheCachingApplicationBlocktouseit
1. ClicktheplussigniconintheBackingStorespane,pointtoAddBackingStoresandclickAddIsolatedStorageCacheStore.
2. (Optional)InthenewIsolatedStorageCacheStoresection,settheNameproperty.
3. SetthePartitionNameproperty.Thisidentifiestheportionofisolatedstoragethatthecachemanagerwilluse.
4. Ifyouwanttoencrypttheinformationstoredinisolatedstorage,youmusthaveconfiguredanencryptionprovider.Toaddanewencryptionprovider,clicktheplussigniconintheEncryptionProviderspaneoftheCachingSettingssection,pointtoAddEncryptionProvidersandthenclickAddSymmetricCryptoProvider(thisistheonlyencryptionprovideroffered).TheconfigurationtoolautomaticallyaddstheCryptographySettingssection.
5. IntheCryptographySettingssection(nottheCachingSettingssection),addasymmetriccryptographyprovidertotheconfiguration.
![Page 295: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/295.jpg)
Forinformationaboutconfiguringthisblock,seeTheCryptographyApplicationBlockdocumentation.
6. IntheCachingSettingssection,selectthenewsymmetricencryptionprovideryouconfiguredintheCryptographySettingssectionoranexistingencryptionproviderinthatsection,inthedrop-downlistfortheSymmetricCryptoProviderproperty.
7. IntheBackingStorespane,intheIsolatedStorageCacheStoresection,settheEncryptionProviderpropertybyselectingtheSymmetricCryptoProvideritemyoujustconfigured.
8. IntheCacheManagerssection,selectthenewbackingstoreyouaddedinthedrop-downlistfortheBackingStorepropertyofthecachemanagerthatwillusethisbackingstore.
Toaddacustomcachestorageprovider1. ClicktheplussigniconintheBackingStorespane,pointtoAdd
BackingStoresandclickAddCustomCacheStorage.2. TheTypeSelectordialogisdisplayed.Navigatetotheassembly
containingyourcustombackingstoreandclickonit.ThestorewillbeaddedanddisplayedintheBackingStorespane.
3. (Optional)Inthenewcustomstoresection,settheNameproperty.4. Ifthecustombackingstorerequiresanyotherconfigurationvaluesto
beprovided,addtheseaskey/valuepairstotheconfigurationbytypingthemintotheKeyandValuetextboxes.Asyouenteravalue,theconfigurationtooldisplaysanewrowinthissection.Clickthecrossbuttontoremoveaname/valuepair.
Ifyouwanttoaddanothercachemanagertoyourapplicationconfiguration,clicktheplussigniconintheCacheManagerspane,pointtoAddCacheManagersandthenclickonthemanageryouwishtoadd.Repeattheprecedingprocedures.Therecanbeonlyonedefaultcachemanager.Eachinstanceofthecachemanagermusthaveauniquename.
![Page 296: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/296.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 297: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/297.jpg)
MicrosoftEnterpriseLibrary5.0
SourceSchemafortheCachingApplicationBlock
ThistopicliststheXMLelementsandattributesusedtoconfiguretheCachingApplicationBlock.YoucanmanuallyedittheXMLdata,buttheEnterpriseLibraryconfigurationtoolsgreatlysimplifythistask.IfyouchoosetomanuallyedittheXML,usetheschemainformationcontainedinthistopic.
Theconfigurationfilehasthefollowingsectionhandlerdeclaration.XML
<configSections>
<sectionname="cachingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings,
Microsoft.Practices.EnterpriseLibrary.Caching"/>
</configSections>
Thesectionhandlerdeclarationcontainsthenameoftheconfigurationsettingssectionandthenameofthesectionhandlerclassthatprocessesconfigurationdatainthatsection.ThenameoftheconfigurationsettingssectioniscachingConfiguration.ThenameofthesectionhandlerclassisMicrosoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings
![Page 298: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/298.jpg)
cachingConfigurationElement
![Page 299: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/299.jpg)
encryptionProvidersElement
![Page 300: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/300.jpg)
backingStoresElement
![Page 301: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/301.jpg)
cacheManagersElement
![Page 302: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/302.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 303: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/303.jpg)
MicrosoftEnterpriseLibrary5.0
AddingApplicationCode
TheCachingApplicationBlockisdesignedtosupportthemostcommonsituationsforstoringdatainacache.Whenaddingyourapplicationcode,refertothescenariosintheKeyScenariossectionsandselecttheonesthatbestsuityoursituation.Usethecodethataccompaniesthescenarioeitherasitis,orreviseitasrequired.
Toprepareyourapplication1. AddareferencetotheCachingApplicationBlockassembly.In
MicrosoftVisualStudio®,right-clickyourprojectnodeinSolutionExplorer,andthenclickAddReference.ClicktheBrowsetabandfindthelocationoftheMicrosoft.Practices.EnterpriseLibrary.Caching.dllassembly.Selecttheassembly,andthenclickOKtoaddthereference.
2. Followthesameproceduretosetareferencetothefollowingassemblies:
Microsoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.Unity.dllMicrosoft.Practices.Unity.Interception.dll
3. Ifyouareusingthedatabasebackingstore,addareferencetoMicrosoft.Practices.EnterpriseLibrary.Caching.Database.dllandMicrosoft.Practices.EnterpriseLibrary.Data.dll.
4. IfyouareusingtheCryptographyApplicationBlocktoencryptdatainthecache,addreferencestoMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.dllandMicrosoft.Practices.EnterpriseLibrary.Caching.Cryptography.dll.
5. (Optional)TouseelementsfromtheCachingApplicationBlockwithoutfullyqualifyingtheelementreference,addthefollowingusingstatements(C#)orImportsstatements(MicrosoftVisualBasic®)tothetopofyoursourcecodefile.C#
![Page 304: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/304.jpg)
usingMicrosoft.Practices.EnterpriseLibrary.Caching;
usingMicrosoft.Practices.EnterpriseLibrary.Caching.Expirations;
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Caching
ImportsMicrosoft.Practices.EnterpriseLibrary.Caching.Expirations
Note:ForVisualBasicprojects,youcanalsousetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer,andthenclick[projectname]PropertiesontheProjectmenu.WhentheProjectDesignerappears,clicktheReferencestab.
Next,addtheapplicationcode.Generally,therearetwostepstocreatecodethatusestheCachingApplicationBlock:
1. ResolveaCacheManagerinstance.2. Calltheappropriatemethods.
Eachkeyscenariodemonstrateshowtoincorporatethesestepsintoanapplication.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 305: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/305.jpg)
MicrosoftEnterpriseLibrary5.0
SelectingaBackingStore
Eachcachemanagercanbeconfiguredtostoredataonlyinmemory,whichmeansthatitusesthenullbackingstore,oreachcachemanagercanbeconfiguredtostoredatabothinmemoryandinpersistentstorage.Thetypeofpersistentstorageisspecifiedwhenyouconfigurethebackingstore.Backingstoresletcacheddatasurviveiftheapplicationmustberestarted.Initsoriginalstate,theCachingApplicationBlocksupportstwotypesofpersistentbackingstores,eachofwhichissuitedtoparticularsituations:
Isolatedstorage–seeUsingtheIsolatedStorageBackingStore.Databasecachestorage–seeUsingtheDataAccessApplicationBlockBackingStore.
Ifyouintendtoperformcachinginamultiple-serverenvironment,suchasaWebfarm,seeConsiderationsforServerScenarios.
Toprotectexternaldatastoresfromunauthorizedaccess,considerthislistofUsageNotes.
DeveloperscanextendtheCachingApplicationBlocktosupportadditionaltypesofbackingstores.Formoreinformationaboutthistopic,seeExtendingandModifyingtheCachingApplicationBlock.
Note:Anapplicationcanusemorethanonecache;eachcachewillberepresentedbyacachemanagerintheapplication'sconfiguration.TheCachingApplicationBlockdoesnotsupporttheuseofthesamepersistentbackingstorelocationbymultiplecachemanagersinanapplication.However,multiplecachemanagersinanapplicationcanhavethesamepartitionname.
![Page 306: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/306.jpg)
UsageNotes
![Page 307: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/307.jpg)
UsingtheNullBackingStore
![Page 309: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/309.jpg)
UsingtheDataAccessApplicationBlockBackingStore
![Page 310: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/310.jpg)
ConsiderationsforServerScenarios
![Page 311: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/311.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 312: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/312.jpg)
MicrosoftEnterpriseLibrary5.0
KeyScenarios
Thissectiondescribesthemostcommonsituationsdevelopersmustaddresswhenstoringdatainacache.Eachscenarioexplainsthetask,givesareal-worldsituationforthetask,andincludescodedemonstratinghowtousetheCachingApplicationBlocktocompletethetask.
AddingItemstotheCache.ThistopicdescribesthebasiccachingoperationssuchashowtoaddanitemtothecacheusingtheAddmethod,settingtheitem'sexpirationpolicy(fortheexpirationprocess)anditspriority(forthescavengingprocess).RemovingItemsfromtheCache.ThistopicdescribeshowtoremoveanitemfromthecacheusingtheRemovemethod.RetrievingItemsfromtheCache.ThistopicdescribeshowtoobtainanitemfromthecacheusingtheGetDatamethod.FlushingtheCache.Thistopicdescribeshowtoflushthecache,whichemptiesit,usingtheFlushmethod.LoadingtheCache.Thistopicdemonstratesproactiveandreactiveloading.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 313: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/313.jpg)
MicrosoftEnterpriseLibrary5.0
AddingItemstotheCache
Cachesstoreitemsthatareeitherexpensivetocreateorexpensivetotransport.Forexample,inaretailapplication,alistofproductsmustbepassedfromthedataaccesscomponentstotheuserinterfacecomponentssothattheproductlistcanbedisplayedtotheusers.Thedatarepresentsreal-worldbusinessentities,suchasproductsororders.Toincreaseperformance,someoftheseitemsmaybeaddedtothecache.
![Page 314: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/314.jpg)
TypicalGoals
![Page 315: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/315.jpg)
Solution
![Page 316: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/316.jpg)
UsingtheAddMethod
![Page 317: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/317.jpg)
RefreshingRemovedItems
![Page 318: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/318.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 319: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/319.jpg)
MicrosoftEnterpriseLibrary5.0
RemovingItemsfromtheCache
Thescavengingandexpirationprocessesautomaticallyremoveitemsfromthecacheaccordingtotheprioritiesandexpirationpoliciesoftheitems.Youcanalsoremovespecificitemsfromthecache.Forexample,inaretailapplication,somedatamaynolongerbeapplicable,dependingonselectionsthecustomermakes.
![Page 320: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/320.jpg)
TypicalGoals
![Page 321: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/321.jpg)
Solution
![Page 322: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/322.jpg)
UsingtheRemoveMethodToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 323: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/323.jpg)
MicrosoftEnterpriseLibrary5.0
RetrievingItemsfromtheCache
Datastoredinthecachemustberetrievedsothatitcanbedisplayedorprocessed.Forexample,inaretailapplication,youmaywanttodisplayalistofproductsfromacatalog.
![Page 324: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/324.jpg)
TypicalGoals
![Page 325: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/325.jpg)
Solution
![Page 326: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/326.jpg)
UsingtheGetDataMethodToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 327: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/327.jpg)
MicrosoftEnterpriseLibrary5.0
FlushingtheCache
Flushingletsyoumanagecacheditemstomakesurethatstorage,memory,andotherresourcesareusedefficiently.Flushingremovesallitemsinthecache,includingthosethathavenotyetexpired.Forexample,inaretailapplication,cacheddatamaynolongerbevalidbecauseofselectionsmadebythecustomerorbecausethecustomerhasloggedoff.
![Page 328: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/328.jpg)
TypicalGoals
![Page 329: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/329.jpg)
Solution
![Page 330: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/330.jpg)
UsingtheFlushMethodToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 331: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/331.jpg)
MicrosoftEnterpriseLibrary5.0
LoadingtheCache
Beforeyoucanusecacheddata,youmustfirstloaddataintothecache.Forexample,inaretailapplication,youmaywanttoloaddataaboutvariousproducts,orallproducts,intothecache.
![Page 332: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/332.jpg)
TypicalGoals
![Page 333: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/333.jpg)
Solution
![Page 334: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/334.jpg)
CachingDataProactively
![Page 336: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/336.jpg)
LoadingExamplesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 337: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/337.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheCachingApplicationBlock
TheCachingApplicationBlockisdesignedspecificallysothat:ItprovidesasetofAPIsthataremanageableinsize.Itenablesdeveloperstoincorporatethestandardcachingoperationsintotheirapplicationswithouthavingtolearntheinternalworkingsoftheblock.ItusestheEnterpriseLibraryconfigurationtoolsforeasyconfiguration.Itperformsefficiently.Itisthreadsafe.Codeisconsideredtobethreadsafewhenitcanbecalledfrommultipleprogrammingthreadswithoutunwantedinteractionamongthosethreads.Itensuresthatthebackingstoreremainsintactifanexceptionoccurswhileitisbeingaccessed.Itensuresthatthestatesofthein-memorycacheandthebackingstoreremainsynchronized.
Thistopicdescribesthedesignofthecachingsystem,describingthehighlightsandspecificdesigndetails.OthertopicsinthissectionincludeDesignoftheExpirationProcessandDesignoftheScavengingProcess.
![Page 338: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/338.jpg)
DesignHighlights
![Page 339: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/339.jpg)
DesignDetailsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 340: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/340.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheExpirationProcess
TheCachingApplicationBlock'sexpirationprocessisperformedbytheBackgroundScheduler.Itperiodicallyexaminesthecacheditemsinthehashtabletoseeifanyitemshaveexpired.YoucontrolhowfrequentlytheexpirationcycleoccurswhenyouconfigureaninstanceoftheICacheManagerinterfacedefaultimplementationCacheManagerbyusingtheconfigurationtools.
TheexpirationpoliciesprovidedwiththeCachingApplicationBlockarethese:Absolute.Thismeanstheitemexpiresataspecifictime.Sliding.Thismeanstheitemexpiresafterthespecifiedtimehaselapsedfromwhentheitemwaslastaccessed.Thedefaulttimeis2minutes.Extendedformat.Thisallowsyoutospecifyverydetailedexpirationconditions.Forexample,youcanspecifythatanitemexpireseverySaturdaynightat10:03PMoronthethirdTuesdayofeachmonth.ExtendedformatsarelistedintheExtendedFormat.csfile.Filedependency.Thismeanstheitemexpireswhenaspecificfileismodified.Neverexpired.Thismeanstheitemwillneverexpire,althoughitmaystillberemovediftheblockdetectsalackofavailablememory.
Thefirstthreepolicies,absolute,sliding,andextendedformat,arereferredtoastime-basedexpirations.Youshouldusetime-basedexpirationforvolatilecacheitems,suchasthosethathaveregulardatarefreshesorthosethatarevalidforonlyaspecifiedtime.Time-basedexpirationletsyousetpoliciesthatkeepitemsinthecacheonlyaslongastheirdataremainscurrent.Forexample,ifyouarewritinganapplicationthattrackscurrencyexchangeratesbyobtainingthedatafromafrequentlyupdatedWebsite,youcancachethecurrencyratesforthetimethatthoseratesremainconstantonthesourceWebsite.Inthissituation,youwouldsetanexpirationpolicythatisbasedonthefrequencyoftheWebsiteupdates.
Thefourthpolicy,filedependency,isreferredtoasanotification-basedexpiration.Itdefinesthevalidityofacacheditembasedonaparticularfile.Ifthefileismodified,thecacheditemisinvalidatedandremovedfromthecache.
TheAddmethodhastwooverloads.Oneoverloadassumesthedefault
![Page 341: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/341.jpg)
expirationpolicy,whichisNeverExpired.Theotheroverloadletsyousettheexpirationpoliciesyourself.Youcanuseasmanypoliciesasyouwant,includingpoliciesthatyoucreateyourself.(FormoreinformationaboutextendingtheCachingApplicationBlockbyaddingyourownexpirationpolicies,seeExtendingandModifyingtheCachingApplicationBlock.)Ifyouhaveanitemwithmultiplepolicies,theitemwillexpireifanyoneofthepolicy'scriteriaismet.
![Page 342: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/342.jpg)
MarkingandSweeping
![Page 343: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/343.jpg)
CallbacksToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 344: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/344.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheScavengingProcess
TheCachingApplicationBlock'sscavengingprocessisperformedbytheBackgroundSchedulerobject.Itchecksthecacheeverytimeanitemisaddedtoseeifthenumberofitemsinthecachehasreachedapredeterminedlimit.Youusetheconfigurationtoolstosetthislimitwhenyouconfigureaninstanceofacachemanager.Youalsosethowmanyitemsareremovedfromthecacheafterscavengingbegins.
Whenanitemisaddedtothecache,thecodecansetoneoffourprioritysettings:Low,Normal,High,orNotRemovable.TheBackgroundSchedulerobjectdetermineswhichitemsshouldbescavengedbydoingamajorsortbasedonpriorityandaminorsortbasedonthelasttimetheitemwasaccessed.Forexample,anitemwithaLowprioritythathasjustbeenusedwillbescavengedbeforesomethingwithaHighprioritythathasnotbeenaccessedforthreeyears.ThedefaultvalueisNormal.
TheNotRemovablepriorityisusedwhenyouwantanitemtoremaininthecacheuntilitexpires.However,thecacheshouldnotbeusedastheonlylocationwhereanitemofdataexists.Acacheshouldbeusedtoimproveperformance;itshouldnotbeusedasaformofpermanentstorage.
Unliketheexpirationprocess,thescavengingprocessperformsmarkingandsweepinginasinglepass.Formoreinformationaboutmarkingandsweeping,seeDesignoftheExpirationProcess.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 345: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/345.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingtheCachingApplicationBlock
Initsoriginalstate,theCachingApplicationBlockworkswellfortypicalcachingsituations.However,theremaybetimeswhenyouhavetocustomizesomeoftheblock'sbehaviortobettersuityourapplication'sparticularrequirements.Therearetwowaystodothis.YoucanextendtheCachingApplicationBlockusingthebuilt-inextensionpoints.Youcanalsomodifytheblockbymakingchangestoitssourcecode.Formoredetails,seethefollowingtopics:
ExtendingtheCachingApplicationBlockExtendingandModifyingEnterpriseLibrary
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 346: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/346.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingtheCachingApplicationBlock
Youextendtheblockthroughdesignatedextensionpoints.Typically,thesearecustomclasses,writtenbyyou,thatimplementaparticularinterfaceorderivefromanabstractclass.Becausethesecustomclassesexistinyourapplicationspace,youdonothavetomodifyorrebuildtheblock.Instead,youdesignateyourextensionsusingconfigurationsettings.
Youcanextendtheblockbyaddinganewtypeofbackingstoreandstorageencryptionprovider,byaddingnewexpirationpolicies,orbyreplacingthedefaultCacheManager.Thefollowingtableliststheinterfacesandbaseclassesthatyoucanusetoextendtheblock.
CustomProviderorExtension InterfaceorBaseClass
BackingStore IBackingStoreorBaseBackingStore
CacheManager ICacheManager
ExpirationPolicy ICacheItemExpiration
StorageEncryptionProvider IStorageEncryptionProvider
FordetailedinformationabouthowtointegratecustomproviderswiththeEnterpriseLibraryconfigurationsystemandconfigurationtoolsseeCreatingCustomProvidersforEnterpriseLibrary.
![Page 347: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/347.jpg)
AddingaNewBackingStore
![Page 348: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/348.jpg)
AddingaNewExpirationPolicy
![Page 349: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/349.jpg)
ReplacingtheDefaultCacheManagerToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 350: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/350.jpg)
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetomakesurethattheinitialdeploymentoftheCachingApplicationBlockisplannedandmanagedandtomakesurethatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheCachingApplicationBlock,seethefollowingtopics:
CachingApplicationBlockPerformanceCountersCachingApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 351: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/351.jpg)
MicrosoftEnterpriseLibrary5.0
CachingApplicationBlockPerformanceCounters
ThefollowingtabledescribestheCachingApplicationBlockperformancecounters.
PerformanceCounter
Description
CacheExpiries/sec
Therateatwhichitemswereexpiredfromthecache.
CacheHitRatio Theratioofcachehitstoreads.Acachehitoccurswhenthecachecontainstherequesteditem.
CacheHits/sec Therateatwhichthecachereceivedrequestsforitemsitcontained.
CacheMisses/sec Therateatwhichthecachereceivedrequestsforitemsitdidnotcontain.
CacheScavengedItems/sec
Therateatwhichitemswerescavengedfromthecache.
Total#ofCacheAccessAttempts
Thetotalnumberofreadsfromthecache.
TotalCacheEntries
Thetotalnumberofitemsinthecache.
TotalCacheExpiries
Thetotalnumberofitemsexpiredfromthecache.
TotalCacheHits Thetotalnumberofrequestsforexistingitemsreceivedbythecache.
TotalCacheMisses
Thetotalnumberofrequestsfornon-existingitemsreceivedbythecache.
TotalCacheScavengedItems
Thetotalnumberofitemsscavengedfromthecache.
TotalUpdated Thetotalnumberofitemsupdatedinthecache.An
![Page 352: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/352.jpg)
Entries updatecanbeeitheran"add"ora"remove"action.
UpdatedEntries/sec
Therateatwhichitemsinthecachewereupdated.Anupdatecanbeeitheran"add"ora"remove"action.
Aratecountersamplesanincreasingcountofeventsovertimeanddividesthevaluesbythechangeintimetodisplayarateofactivity.Formoreinformationaboutperformancecounters,seeOverviewofPerformanceMonitoringinthe.NETFrameworkClassLibraryonMSDN.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 353: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/353.jpg)
MicrosoftEnterpriseLibrary5.0
CachingApplicationBlockEventLogEntries
ThistopicliststheCachingApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
![Page 354: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/354.jpg)
CacheFailedEvent
![Page 355: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/355.jpg)
CacheCallbackFailedEvent
![Page 356: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/356.jpg)
ConfigurationErrorEvent
![Page 357: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/357.jpg)
ConfigurationChangedEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 358: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/358.jpg)
MicrosoftEnterpriseLibrary5.0
TheCryptographyApplicationBlock
Developersfrequentlywriteapplicationsthatrequireencryptionandhashingcapabilitiestomeetthesecurityrequirementsoftheirorganization.Datathatiscreatedandmaintainedbyapplications,aswellasconfigurationinformation,oftenneedstobeencrypted.Additionally,passwordsthatareusedtoaccessapplicationfunctionalityordataneedtobehashed.
TheEnterpriseLibraryCryptographyApplicationBlocksimplifiesthewaydevelopersincorporatecryptographicfunctionalityintheirapplications.Applicationscanusetheblockforavarietyoftasks,suchasencryptinginformation,creatingahashfromdata,andcomparinghashvaluestoverifythatdatahasnotbeenaltered.Inaddition,youcanchangetheunderlyingprovidersthroughconfigurationwithoutchangingtheunderlyingapplicationcode.
TheCryptographyApplicationBlockincludessupportforthefollowingfeatures:
EncryptionalgorithmsHashingalgorithmsMultiplecryptographyprovidersAdditionalimplementationsofcryptographyprovidersKeyprotectionwiththedataprotectionAPI(DPAPI)
ThissectionincludesthefollowingtopicsthatwillhelpyoutounderstandandusetheCryptographyApplicationBlock:
WhatDoestheCryptographyApplicationBlockDo?Thistopicprovidesabriefoverviewthatwillhelpyoutounderstandwhattheblockcando,andexplainssomeoftheconceptsandfeaturesitincorporates.Italsoprovidesasimpleexampleofwritingcodetousetheblock.WhenShouldIUsetheCryptographyApplicationBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andanyalternativetechniquesyoumayconsider.Italsoprovidesdetailsofanylimitationsoftheblockthatmayaffectyourdecisiontouseit.DevelopingApplicationsUsingtheCryptographyApplicationBlock.ThistopicdescribeshowtoinstalltheCryptographyApplicationBlocksothatyoucanuseitinyourapplications.Italsodescribeshowto
![Page 359: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/359.jpg)
configuretheblockforcommonoperations.KeyScenarios.Thistopicthenshowshowtousetheblocktoperformmostcryptographytasks.DesignoftheCryptographyApplicationBlock.Thistopicexplainsthedecisionsthatwentintothedesignoftheblockandtherationalebehindthosedecisions.ExtendingandModifyingtheCryptographyApplicationBlock.ThistopicexplainshowtoextendtheCryptographyApplicationBlockbycreatingyourownprovidersandhowtomodifythesourcecode.DeploymentandOperations.Thistopicexplainshowtodeployandupdatetheblock'sassemblies.Italsocontainsinformationaboutconfiguration.
![Page 360: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/360.jpg)
MoreInformationFormoreinformation,seethefollowingresources:
ImprovingWebApplicationSecurity:ThreatsandCountermeasuresHowTo:UseAuthorizationManager(AzMan)withASP.NET2.0patterns&practicesSecurityHowToIndex
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 361: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/361.jpg)
MicrosoftEnterpriseLibrary5.0
WhatDoestheCryptographyApplicationBlockDo?
TheCryptographyApplicationBlockconsistsofafacadethatallowsyoutoaccessthetwotypesofproviderscontainedwithintheblock.Thesetwotypesofprovidersare:
Hashingproviders.Theseproviderscanbeusedtogenerateahashfromavalueyousupply,andcomparetwohashvalues.Theblockincludeshashprovidersthatusearangeofcommonhashingalgorithms.Cryptographyproviders.Theseproviderscanbeusedtoencryptanddecryptvaluesthatyousupply.Theblockincludescryptographyprovidersthatusearangeofcommonencryptionalgorithms.
Whenyouusethecryptographyproviderstoencryptavalue,youcanspecifythevalueasanarrayofbytes,andthemethodwillreturntheresultasanarrayofbytes.Alternatively,youcanspecifytheinputvalueasastring,andthemethodswillreturntheresultasabase-64encodedstring.Themethodsthatdecryptvaluesworkthesameway,exceptthatstringvaluesreturnedbythemethodsarenotbase-64encoded.
Whenyouusethehashingproviderstocreateahash,youcanspecifythevaluetohashasanarrayofbytes,andthemethodwillreturntheresultasanarrayofbytes.Alternatively,youcanspecifytheinputvalueasastring,andthemethodswillreturntheresultasastring.Themethodsthatcomparehashvaluesaccepteitheranarrayofbytesorastring,andreturneithertrueorfalse.
![Page 362: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/362.jpg)
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 363: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/363.jpg)
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheCryptographyApplicationBlock?
YoushouldusetheCryptographyApplicationBlockwhenyouneedhashingand/orsymmetricencryptionfunctionality.Youcanusethesefunctionsinconjunctionwiththecryptographicprovidersincludedwiththeblockorwithyourowncustomcryptographicproviders.Ifthedataonlyneedstobeencrypted,anditdoesnotneedtobedecrypted(forexample,apassword),youcanusehashing.Ifthedataneedstobebothencryptedanddecrypted(forexample,totransmitsensitivecustomerdata),youcanusesymmetricencryption.
![Page 364: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/364.jpg)
ScenariosfortheCryptographyApplicationBlock
![Page 365: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/365.jpg)
BenefitsoftheCryptographyApplicationBlock
![Page 366: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/366.jpg)
LimitationsoftheCryptographyApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 367: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/367.jpg)
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheCryptographyApplicationBlock
ThistopicdescribeshowtodevelopapplicationsusingtheCryptographyApplicationBlock.Itexplainshowtomodifytheconfigurationoftheblocktoperformparticulartasksandhowtousetheblockforparticularscenarios,suchasencryptingdata.Thistopicassumesthatyouareusingtheblockinitsoriginalstate,withoutextendingit.(Tolearnhowtoaddfunctionality,seeExtendingandModifyingtheCryptographyApplicationBlock.)Thissectionincludesthefollowingtopics:
EnteringConfigurationInformationAddingApplicationCode
Allapplicationblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompileit.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 368: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/368.jpg)
MicrosoftEnterpriseLibrary5.0
EnteringConfigurationInformation
TheseproceduresexplainhowtoconfiguretheCryptographyApplicationBlock.AlsoseeUsingtheCryptographicKeyWizard.Fordetailsoftheconfigurationschema,seeSourceSchemafortheCryptographyApplicationBlock.Youcanalsoconfiguretheblockincodebyusinganalternateconfigurationsource.Formoreinformation,seeAdvancedConfigurationScenariosandUsingtheFluentConfigurationAPI.
ToaddtheCryptographyApplicationBlock1. Opentheconfigurationfile.Formoreinformation,seeConfiguring
EnterpriseLibrary.2. OpentheBlocksmenuandthenclickAddCryptographySettings.3. TheconfigurationtoolautomaticallyaddstheCryptographySettings
section,andtheHashProvidersandSymmetricCryptographyProviderssubsections,withdefaultsettings.
4. ToeditthepropertiesoftheCryptographySettingssection,clickthepropertyexpanderchevron.
Toconfigureahashalgorithmprovider1. ClicktheHashProvidersplussignicon,pointtoAddHash
Providers,andthenclickAddHashAlgorithmProvider.2. Inthetypeselectordialog,selectthehashalgorithmprovidertypeyou
wanttouse.Ifthehashproviderisnotincluded,clickAddfromFileorAddfromGACtolocatetheassemblythatcontainstherequiredtype.
3. (Optional)IntheNamepropertytextbox,changethenameofthehashalgorithmprovider.Thedefaultnameisthetypenameyouselectedinstep2.
4. SettheSaltEnabledpropertybyclickingTrueorFalseinthedrop-downlist.ThedefaultisTrue.
Note:TheCryptographicKeyWizardappearsforkeyedhashalgorithmproviders.Forinformationaboutgeneratingandimportingkeys,seethesectionUsing
![Page 369: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/369.jpg)
theCryptographicKeyWizardlaterinthistopic.
Toconfigureacustomhashprovider1. ClicktheHashProvidersplussignicon,pointtoAddHash
Providers,andthenclickAddCustomHashProvider.
2. Inthetypeselectordialogeithertypethefullpathnameforacustomhashproviderornavigatetoitinthelist.Youcanfiltertheclassesdisplayedbytypinginthetextbox.Toaddacustomproviderfromanotherassembly,clickAddfromFileandnavigatetotheassemblyfile.Toaddaproviderstoredintheglobalassemblycache(GAC),clickAddfromGAC.
3. (Optional)AddcustomAttributesKey/Valuepairsintheeditbox.
4. (Optional)SettheNamepropertybytypingthenameintheeditbox.ThedefaultnameisthenameofthetypeselectedbyusingtheTypeSelectortool.
ToconfigureaDPAPIsymmetriccryptographyprovider1. ClicktheSymmetricCryptographyProvidersplussignicon,pointto
AddSymmetricCryptographyProviders,andthenclickAddDPAPISymmetricCryptoProvider.
![Page 370: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/370.jpg)
2. (Optional)ChangetheNamepropertyoftheDPAPIsymmetriccryptographyprovider.ThedefaultnameisDPAPISymmetricCryptoProvider.
3. SettheProtectionScopeproperty.Inthedrop-downlist,clickCurrentUserorLocalMachine.TheCurrentUservaluemeansthatDPAPIusesaloadeduserprofiletogeneratethekey.Onlythatparticularuseraccountcandecrypttheencrypteddata.TheLocalMachinevaluemeansthatthatanycoderunningonthemachinehasaccesstotheprotectedkey;therefore,itcandecryptanysecretencryptedinLocalMachinemode.Tocounteractthis,yourapplicationcodecanpassanentropyvaluewhenitcallstheEncryptorDecryptmethods.Entropymakesitmoredifficultforoneapplication,runningonthesamecomputer,tocompromiseanotherapplication'sencryptionkey.However,youmustprotecttheentropyvalue.Ifitissimplysavedtoanunprotectedfile,attackerscanaccessthefile,retrievetheentropyvalue,anduseittodecryptanapplication'sdata.TheCryptographyApplicationBlockconfigurationdoesnotincludetheentropyvalue.Thismeansthatyoucannotusetheconfigurationtoolstocreateorsaveanentropyvalue.
Toconfigureasymmetricalgorithmprovider1. ClicktheSymmetricCryptographyProvidersplussignicon,pointto
AddSymmetricCryptographyProviders,andthenclickAddSymmetricAlgorithmProvider.
2. Inthetypeselectordialog,selectthesymmetricalgorithmprovidertypeyouwanttouse.Youcanfiltertheclassesdisplayedbytypinginthetextbox.Toaddacustomproviderfromanotherassembly,clickAddfromFileandnavigatetotheassemblyfile.Toaddaproviderstoredintheglobalassemblycache,clickAddfromGAC.
3. Afterselectingthealgorithmprovider,theCryptographicKeyWizardwillruntoeitherimportorgenerateakey.FormoreinformationonusingtheWizard,seeUsingtheCryptographicKeyWizard.
![Page 371: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/371.jpg)
4. OnthefinalpageoftheWizardclickonFinishtoaddthenewprovider.
Toconfigureacustomsymmetriccryptographyprovider1. ClicktheSymmetricCryptographyProvidersplussignicon,pointto
AddSymmetricCryptographyProviders,andthenclickAddCustomSymmetricCryptoProvider.
2. Inthetypeselectordialogeithertypethefullpathnameforthecustomsymmetriccryptographyproviderornavigatetoit.Youcanfiltertheclassesdisplayedbytypinginthetextbox.Toaddacustomproviderfromanotherassembly,clickAddfromFileandnavigatetotheassemblyfile.Toaddaproviderstoredintheglobalassemblycache,clickAddfromGAC.
3. (Optional)AddcustomAttributesKey/Valuepairsintheeditbox.4. (Optional)IntheNamepropertytextbox,changethenameofthe
customsymmetriccryptographyprovider.ThedefaultnameisthenameofthetypeselectedbyusingtheTypeSelectortool.
Toconfigurethedefaultprovidersfortheblock1. OpentheCryptographySettingspropertiesbyeitherrightclickingon
theCryptographySettingssectionorbyclickingonthepropertyexpanderchevron.
![Page 372: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/372.jpg)
2. (Optional)Inthepropertiespane,settheDefaultHashProviderproperty.ThissetstheinstanceofthehashproviderthattheCryptographyApplicationBlockusesiftheapplicationcodedoesnotspecifyanotherprovider.Inthedrop-downlist,clickthehashprovider.Thedefaultisnone.
3. (Optional)Inthepropertiespane,settheDefaultSymmetricCryptoProviderproperty.ThissetstheinstanceofthesymmetriccryptographyproviderthattheCryptographyApplicationBlockusesiftheapplicationcodedoesnotspecifyanotherprovider.Inthedrop-downlist,clickthesymmetricprovider.Thedefaultisnone.
![Page 373: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/373.jpg)
UsingtheCryptographicKeyWizard
![Page 374: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/374.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 375: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/375.jpg)
MicrosoftEnterpriseLibrary5.0
SourceSchemafortheCryptographyApplicationBlock
ThistopicliststheXMLelementsandattributesusedtoconfiguretheCryptographyApplicationBlock.YoucanmanuallyedittheXMLdata,buttheEnterpriseLibraryconfigurationtoolsgreatlysimplifythistask.IfyouchoosetomanuallyedittheXML,usetheschemainformationcontainedinthistopic.
Theconfigurationfilehasthefollowingsection-handlerdeclaration.XML
<sectionname="securityCryptographyConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration.CryptographySettings,
Microsoft.Practices.EnterpriseLibrary.Security.Cryptography"/>
Thesection-handlerdeclarationcontainsthenameoftheconfigurationsettingssectionandthenameofthesection-handlerclassthatprocessesconfigurationdatainthatsection.ThenameoftheconfigurationsettingssectionissecurityCryptographyConfiguration.Thenameofthesection-handlerclassisCryptographySettings.ItisintheMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.Configurationnamespace.
![Page 376: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/376.jpg)
securityCryptographyConfigurationElement
![Page 377: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/377.jpg)
hashProvidersChildElement
![Page 378: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/378.jpg)
symmetricCryptoProvidersChildElement
![Page 379: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/379.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 380: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/380.jpg)
MicrosoftEnterpriseLibrary5.0
MaximizingSecurity
TwoimportantpointsyoushouldconsiderwhenyouusetheCryptographyApplicationBlockarehowyouaregoingtomanagesymmetricencryptionkeysandwhichhashingalgorithmorsymmetricencryptionalgorithmyouaregoingtouse.
![Page 381: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/381.jpg)
ManagingandDistributingKeys
![Page 382: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/382.jpg)
SelectinganEncryptionAlgorithmToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 383: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/383.jpg)
MicrosoftEnterpriseLibrary5.0
AddingApplicationCode
TheCryptographyApplicationBlockisdesignedtosupportcommonscenariosforsymmetricencryptionandhashing.Whenyouaddyourapplicationcode,refertothescenariosinKeyScenariosandselecttheonesthatbestsuityoursituation.Usethecodethataccompaniesthescenarioeitherasitisshownhereoradaptitasneeded.
Toprepareyourapplication1. AddareferencetotheCryptographyApplicationBlockassembly.In
VisualStudio®,right-clickyourprojectnodeinSolutionExplorer,andthenclickAddReference.ClickBrowsetolocatetheMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.dllassembly.Selecttheassembly,andthenclickOK.
2. Followingthesameprocedure,setareferencetothefollowingassemblies:
Microsoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.Unity.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.Unity.Interception.dll
3. (Optional)TouseelementsfromtheCryptographyApplicationBlockwithoutfullyqualifyingtheelementreference,youcanaddthefollowingusingstatement(C#)orImportsstatement(VisualBasic)tothetopofyoursourcecodefile.C#
usingMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography;
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography
4. Next,addtheapplicationcode.
![Page 384: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/384.jpg)
Note:ForMicrosoft®VisualBasic®projects,youcanalsousetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer,andthenclickPropertiesontheProjectmenu.WhentheProjectDesignerappears,clicktheReferencestab.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 385: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/385.jpg)
MicrosoftEnterpriseLibrary5.0
KeyScenarios
Thistopicdescribesthemostcommonsituationsthatdevelopersmustaddresswhenprovidingcryptographyfunctionalityintheirapplications.Eachscenarioexplainsthetask,describesareal-worldsituationwheresuchataskmightoccur,andincludescodethatdemonstrateshowtousetheCryptographyApplicationBlocktocompletethetask.Thescenariosarethefollowing:
EncryptingDataUsingaSymmetricProvider.Thisscenarioillustrateshowyoucanuseasymmetricalgorithmprovidertoencryptasecret.DecryptingDataUsingaSymmetricProvider.Thisscenarioillustrateshowyoucanuseasymmetricalgorithmprovidertodecryptasecretthathasbeenencrypted.ObtainingaHashValue.Thisscenarioillustrateshowyoucangenerateahashvaluefromdata.CheckingWhetheraHashValueMatchesSomeText.Thisscenarioillustrateshowyoucancompareplaintextdatawithahashvaluepreviouslygeneratedfromthedata.Bydoingthis,youcanverifythatthedatahasnotbeenchangedsincethehashwasoriginallygenerated.
Note:Thenon-staticfacadenamedCryptographyManagerreplacesthestaticCryptographerfacadeusedinpreviousversionsofEnterpriseLibrary.However,codethatusestheCryptographerfacadewillcontinuetoworkinthisrelease.ForinformationaboutresolvingEnterpriseLibraryobjectsinyourapplications,seeCreatingandReferencingEnterpriseLibraryObjects.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 386: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/386.jpg)
MicrosoftEnterpriseLibrary5.0
EncryptingDataUsingaSymmetricProvider
Acommoncryptographytaskistoencryptdatausingasymmetricprovider.Youmaywanttodothiswhenanapplicationhasdatayouwanttokeepsecure.
![Page 387: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/387.jpg)
TypicalGoals
![Page 388: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/388.jpg)
Solution
![Page 389: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/389.jpg)
UsingEncryptSymmetric
![Page 390: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/390.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 391: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/391.jpg)
MicrosoftEnterpriseLibrary5.0
DecryptingDataUsingaSymmetricProvider
Ifyouencryptdatabyusingasymmetricencryptionprovider,youusuallyhavetodecryptthedatausingthesameprovider.
![Page 392: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/392.jpg)
TypicalGoals
![Page 393: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/393.jpg)
Solution
![Page 394: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/394.jpg)
UsingDecryptSymmetric
![Page 395: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/395.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 396: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/396.jpg)
MicrosoftEnterpriseLibrary5.0
ObtainingaHashValue
Anexampleofwhenyoumightwanttoobtainahashvalueiswhenyouhaveapasswordthatyoudonotwanttopassoverthenetwork.
![Page 397: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/397.jpg)
TypicalGoals
![Page 398: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/398.jpg)
Solution
![Page 399: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/399.jpg)
UsingCreateHash
![Page 400: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/400.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 401: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/401.jpg)
MicrosoftEnterpriseLibrary5.0
CheckingWhetheraHashValueMatchesSomeText
Anexampleofwhenyouwouldcheckwhetherahashmatchessometextiswhenyouhavetoverifythatdatahasnotbeenchangedintransitoveranetwork.Inthiscase,thehashvalueforthedatawouldbestoredattheserver,andwhenthedataarrivesattheserver,itiscomparedagainstthehashvalue.
![Page 402: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/402.jpg)
TypicalGoals
![Page 403: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/403.jpg)
Solution
![Page 404: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/404.jpg)
UsingCompareHash
![Page 405: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/405.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 406: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/406.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheCryptographyApplicationBlock
Thistopicdescribesthedesigngoals,designhighlights,andtheimplementationoftheCryptographyApplicationBlock.
![Page 407: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/407.jpg)
DesignGoals
![Page 408: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/408.jpg)
DesignHighlights
![Page 409: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/409.jpg)
KeyManagementModelToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 410: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/410.jpg)
MicrosoftEnterpriseLibrary5.0
DesigningforSimplifiedCryptographyFunctionality
Cryptographyinapplicationscanbeimplementedinmanyways.Typically,developersmustduplicatecodetoperformcommontasks.Tomeettheneedsoftheirorganization,theymayhavetofamiliarizethemselveswithmanydifferentwaysofimplementingcryptography.TheCryptographyApplicationBlockisdesignedtosimplifyandabstracttheimplementationofcryptographyinapplications.
![Page 411: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/411.jpg)
DesignImplications
![Page 412: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/412.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 413: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/413.jpg)
MicrosoftEnterpriseLibrary5.0
DesigningforAlgorithmAbstraction
WiththeCryptographyApplicationBlock,developerscanrefertothealgorithmtobeusedbythevariousmethodsbyusinglogicalnames,suchas"hashprovider"or"passwordencryption."
![Page 414: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/414.jpg)
DesignImplications
![Page 415: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/415.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 416: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/416.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingtheCryptographyApplicationBlock
Initsoriginalstate,theCryptographyApplicationBlockworkswellfortypicalcryptographyscenarios.However,theremaybetimeswhenyouhavetocustomizesomeoftheblock'sbehaviortobettersuityourapplication'sparticularrequirements.Therearetwowaystocustomizetheblock,extensionandmodification.
![Page 417: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/417.jpg)
ExtendingtheCryptographyApplicationBlock
![Page 418: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/418.jpg)
ModifyingtheCryptographyApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 419: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/419.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingtheCryptographyApplicationBlock
TheCryptographyApplicationBlockisdesignedtobeusedinavarietyofapplicationsandtobeageneral-purposeblock.Extensionpointsletyouadapttheblocktosuittheneedsofanyparticularapplication.Youcanextendthecapabilitiesoftheblockbyaddingcustomcryptographyproviders.Typically,thesecustomprovidersarethird-partycryptographyproviders.Thefollowingtableliststheinterfacesthatyoucanusetoextendtheblock.
CustomProviderorExtension Interface
HashAlgorithmProvider IHashProvider
SymmetricEncryptionAlgorithmProvider ISymmetricCryptoProvider
ToextendtheCryptographyApplicationBlock1. Createanewcustomclassandaddittoyourproject.2. Makesuretheclassimplementstherequiredinterfaces,constructors,
andmethods.3. ConfigurethegenericproviderintheEnterpriseLibraryconfiguration
tools:Specifyyourcustomclassasthetypename.Specifyanycustomconfigurationpropertiesbymodifyingtheattributesoftheobject.
Tocreateacustomhashalgorithmprovider1. Createanewclass,andthenaddittoyourproject.2. (Optional)Touseelementswithoutfullyqualifyingtheelement
reference,youcanaddthefollowingusingstatement(C#)orImportsstatement(VisualBasic)tothetopofyoursourcecodefile.C#
usingMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography;
usingMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration;
![Page 420: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/420.jpg)
CopyCode
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography
ImportsMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration
Note:ForVisualBasicprojects,youcanalsousetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer,andthenclick[projectname]PropertiesontheProjectmenu.WhentheProjectDesignerappears,clicktheReferencestab.
3. SpecifythattheclassimplementsIHashProvider.4. AddtheclassattributeConfigurationElementType.Specifythetype
CustomHashProviderDataastheattributeparameter.C#
[ConfigurationElementType(typeof(CustomHashProviderData))]
publicclassMyHashProvider:IHashProvider
VisualBasic
<ConfigurationElementType(GetType(CustomHashProviderData))>_
PublicClassMyHashProvider
ImplementsIHashProvider
5. AddaconstructorthathasaparameteroftypeNameValueCollection.C#
publicMyHashProvider(NameValueCollectionattributes)
{
}
VisualBasic
![Page 421: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/421.jpg)
PublicSubNew(ByValattributesAsNameValueCollection)
EndSub
6. AddtheCreateHashandCompareHashmethodstoyourclass,andthenimplementtherequiredbehavior.C#
publicbyte[]CreateHash(byte[]plaintext)
{
}
publicboolCompareHash(byte[]plaintext,byte[]hashedtext)
{
}
VisualBasic
PublicFunctionCreateHash(ByValplaintextAsByte())AsByte()
EndFunction
PublicFunctionCompareHash(ByValplaintextAsByte(),ByValhashedtextAsByte())AsBoolean
EndFunction
Tocreateacustomsymmetricencryptionalgorithmprovider1. Createanewclass,andthenaddittoyourproject.2. (Optional)Touseelementswithoutfullyqualifyingtheelement
reference,youcanaddthefollowingusingstatement(C#)orImportsstatement(VisualBasic)tothetopofyoursourcecodefile.C#
usingMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography;
usingMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration;
![Page 422: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/422.jpg)
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography
ImportsMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration
Note:ForVisualBasicprojects,youcanalsousetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer,andthenclick[projectname]PropertiesontheProjectmenu.WhentheProjectDesignerappears,clicktheReferencestab.
3. SpecifythattheclassimplementsISymmetricCryptoProvider.4. AddtheclassattributeConfigurationElementType.Specifythetype
CustomSymmetricCryptoProviderDataastheattributeparameter.C#
[ConfigurationElementType(typeof(CustomSymmetricCryptoProviderData))]
publicclassMyCustomEncryptionProvider:ISymmetricCryptoProvider
VisualBasic
<ConfigurationElementType(GetType(CustomSymmetricCryptoProviderData))>_
PublicClassMyCustomEncryptionProvider
ImplementsISymmetricCryptoProvider
5. AddaconstructorthathasaparameteroftypeNameValueCollection.C#
publicMyCustomEncryptionProvider(NameValueCollectionattributes)
{
}
VisualBasic
![Page 423: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/423.jpg)
CopyCode
PublicSubNew(ByValattributesAsNameValueCollection)
EndSub
6. AddtheEncryptandDecryptmethodstoyourclass,andthenimplementtherequiredbehavior.C#
publicbyte[]Encrypt(byte[]plaintext)
{
}
publicbyte[]Decrypt(byte[]ciphertext)
{
}
VisualBasic
PublicFunctionEncrypt(ByValplaintextAsByte())AsByte()
EndFunction
PublicFunctionDecrypt(ByValciphertextAsByte())AsByte()
EndFunction
FordetailedinformationabouthowtointegratecustomproviderswiththeEnterpriseLibraryconfigurationsystemandconfigurationtoolsseeCreatingCustomProvidersforEnterpriseLibrary.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 424: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/424.jpg)
MicrosoftEnterpriseLibrary5.0
ModifyingtheCryptographyApplicationBlock
TheCryptographyApplicationBlockwasdesignedtobeusedinavarietyofapplicationsandtobeageneral-purposecryptographyapplicationblock.Extensionpointsletyouadapttheblocktosuittherequirementsofanyparticularapplication.However,ifyouwanttoaddnewfeaturestotheblock,youcandosobymodifyingthesourcecode(theblockincludesboththesourcecodeandthebinaries).
Note:Whenmodifyingthesourcecode,youshouldfollowgoodpracticesdescribedinthetopicExtendingandModifyingEnterpriseLibrary.
![Page 425: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/425.jpg)
ModifyingtheKeyManagementCode
![Page 426: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/426.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 427: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/427.jpg)
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetomakesurethattheinitialdeploymentoftheCryptographyApplicationBlockisplannedandmanagedandtomakesurethatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheblock.Fordetails,seeDeployingtheCryptographyApplicationBlock.
Inaddition,administratorsmustdecideiftheywanttousetheinstrumentationexposedbytheblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationontheinstrumentationcontainedwithintheCryptographyApplicationBlock,seethefollowingtopics:
CryptographyApplicationBlockPerformanceCountersCryptographyApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 428: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/428.jpg)
MicrosoftEnterpriseLibrary5.0
DeployingtheCryptographyApplicationBlock
TheCryptographyApplicationBlockiscomprisedofmultipleassemblies.EachassemblythatbelongstotheCryptographyApplicationBlockhasafilenamethatbeginswithMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.Additionally,theblockdependsonthecommonassemblyandontheUnitysubsystem.FordetailsofdeployingandupdatingEnterpriseLibraryandtheblocks,seeDeployingEnterpriseLibrary.
![Page 429: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/429.jpg)
DistributingKeysToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 430: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/430.jpg)
MicrosoftEnterpriseLibrary5.0
CryptographyApplicationBlockPerformanceCounters
ThefollowingtabledescribestheCryptographyApplicationBlockperformancecounters.
PerformanceCounter Description
HashComparisons/sec Therateatwhichhashcomparisonswereperformed.
HashMismatches/sec Therateatwhichhashcomparisonmismatchesweredetected.
HashOperations/sec Therateatwhichplaintextwashashed.
SymmetricDecryptions/sec
Therateatwhichsymmetricdecryptionswereperformed.
SymmetricEncryptions/sec
Therateatwhichsymmetricencryptionswereperformed.
TotalHashComparisons
Thetotalnumberofhashcomparisonsperformed.
TotalHashMismatches Thetotalnumberofhashcomparisonmismatchesdetected.
TotalHashOperations Thetotalnumberofplaintexthashingoperationsperformed.
TotalSymmetricDecryptions
Thetotalnumberofsymmetricdecryptionsperformed.
TotalSymmetricEncryptions
Thetotalnumberofsymmetricencryptionsperformed.
Aratecountersamplesanincreasingcountofeventsovertimeanddividesthevaluesbythechangeintimetodisplayarateofactivity.Formoreinformationaboutperformancecounters,seeOverviewofPerformanceMonitoringinthe.NETFrameworkClassLibraryonMSDN.
![Page 431: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/431.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 432: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/432.jpg)
MicrosoftEnterpriseLibrary5.0
CryptographyApplicationBlockEventLogEntries
ThistopicliststheCryptographyApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
![Page 433: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/433.jpg)
CryptographicOperationFailedEvent(SymmetricAlgorithm)
![Page 434: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/434.jpg)
CryptographicOperationFailedEvent(HashAlgorithm)
![Page 435: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/435.jpg)
ConfigurationFailureEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 436: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/436.jpg)
MicrosoftEnterpriseLibrary5.0
TheDataAccessApplicationBlock
TheEnterpriseLibraryDataAccessApplicationBlocksimplifiesthedevelopmentoftasksthatimplementcommondataaccessfunctionality.Applicationscanusethisapplicationblockinavarietyofsituations,suchasreadingdatafordisplay,passingdatathroughapplicationlayers,andsubmittingchangeddatabacktothedatabasesystem.
TheapplicationblockincludessupportforbothstoredproceduresandinlineSQLstatements.Commonhousekeepingtasks,suchasmanagingconnectionsandcreatingandcachingparameters,areencapsulatedintheapplicationblock'smethods.Inotherwords,theDataAccessApplicationBlockprovidesaccesstothemostoftenusedfeaturesofADO.NETinsimple-to-useclassesandprovidesacorrespondingboostindeveloperproductivity.
ThissectionincludesthefollowingtopicsthatwillhelpyoutounderstandandusetheDataAccessApplicationBlock:
WhatDoestheDataAccessApplicationBlockDo?Thistopicprovidesabriefoverviewthatwillhelpyoutounderstandwhattheblockcando,andexplainssomeoftheconceptsandfeaturesitincorporates.Italsoprovidesasimpleexampleofthewaythatyoucanwritecodetousetheblock.WhenShouldIUsetheDataAccessApplicationBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andanyalternativetechniquesyoumayconsider.Italsoprovidesdetailsofanylimitationsoftheblockthatmayaffectyourdecisiontouseit.DevelopingApplicationsUsingtheDataAccessApplicationBlock.Thisdescribeshowtoconfiguretheapplicationblock,howtoprepareyourapplicationtousetheDataAccessApplicationBlock,andcontainsdetailsofspecificfeaturesoftheapplicationblock,suchashowyoucreateadatabase,workwithtransactions,andhandleparametersandexceptions.KeyScenarios.Thissectiondemonstrateshowtousetheapplicationblocktoperformthemosttypicaldataaccessoperations.DesignoftheDataAccessApplicationBlock.Thissectiondescribesthe
![Page 437: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/437.jpg)
decisionsthatwentintodesigningtheapplicationblockandtherationalebehindthosedecisions.ExtendingandModifyingtheDataAccessApplicationBlock.Thissectiondescribeshowtoextendtheapplicationblockbyaddingyourowndatabaseproviderandgivessuggestionsformodifyingthesourcecode.DeploymentandOperations.Thissectiondescribeshowtodeployandupdatetheapplicationblockassemblies.ItalsocontainsinformationaboutconfigurationandMicrosoft®SQLServer®security.
![Page 438: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/438.jpg)
MoreInformationFormoreinformation,seethefollowingresources:
MicrosoftApplicationArchitectureGuide,2ndEdition-Chapter8:DataLayerGuidelines.NETDataAccessArchitectureGuideINFO:MicrosoftGuideforDesigningDataTierComponentsandPassingDataThroughTiersImprovingWebApplicationSecurity:ThreatsandCountermeasuresImproving.NETApplicationPerformanceandScalability
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 439: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/439.jpg)
MicrosoftEnterpriseLibrary5.0
WhatDoestheDataAccessApplicationBlockDo?
TheDataAccessApplicationBlockincludesasmallnumberofmethodsthatsimplifythemostcommontechniquesforaccessingadatabase.Eachmethodencapsulatesthelogicrequiredtoretrievethedataandmanagetheconnectiontothedatabase.Themethodsexposedbytheblockallowyoutoexecutequeries,returndatainarangeofdifferentformats,populateaDataSet,updatethedatabasefromaDataSet,performdataaccessasynchronously(againstSQLServerdatabases),andreturndataasobjectsinasuitableformatforusewithclient-sidequerytechnologiessuchasLINQ.
ADO.NETprovidesclassessuchastheDbCommandclassandtheDbConnectionclass;theseclasseshelptoabstractthedataproviderfromanyparticulardatabaseimplementation.TheDataAccessApplicationBlocktakesadvantageoftheseclassesandprovidesamodelthatfurthersupportsencapsulationofspecificfeaturesofeachdatabasetype,suchasparameterdiscoveryandtypeconversion.Asaresult,applicationscanoftenbeportedfromonedatabasetypetoanotherwithoutmodifyingtheclientcode.TheDataAccessApplicationBlockincludesanabstractbaseclassthatdefinesacommoninterfaceandprovidesmuchoftheimplementationrequiredbythedataaccessmethodsavailableinADO.NET.
TheapplicationblockalsoincludesclassesdesignedtoworkwithMicrosoftSQLServer,MicrosoftSQLServerCE,andOracle.Theseclassesperformoperationsthatarespecifictothedatabasetype.Thecodeforapplicationswrittenforonetypeofdatabase,suchasSQLServer,looksmuchthesameasthecodeforapplicationswrittenforanothertypeofdatabasesuchasOracle.
AnotherfeatureoftheDataAccessApplicationBlockisthatapplicationcodecanrefertoparticulardatabasesbyanADO.NETconnectionstringname,suchas"Customer"or"Inventory."TheapplicationcodecanspecifyanamedinstanceofadatabasewhencreatingtheDatabaseimplementationitusesasafacadeforthemajorityofthemethods.Eachnameddatabasehasitsconnectioninformationstoredinaconfigurationfile.Bychangingthesettingsintheconfigurationfile,developerscanusetheirapplicationswithdifferentdatabasetypeswithoutrecompilingtheircode.
![Page 440: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/440.jpg)
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 441: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/441.jpg)
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheDataAccessApplicationBlock?
YoushouldconsiderusingtheDataAccessApplicationBlockifyourapplicationusesstandarddataaccesstechniques.Theblockisparticularlysuitedtoquerying,retrieving,andupdatingdatathroughimplementationsbasedontheExecuteReader,ExecuteXmlReader,andExecuteNonQuerymethodscommonlyusedinADO.NET—includingtheasynchronousversionsofthesemethods.ItalsoprovidesmethodstopopulateDataSetinstances,andflushthechangesbacktothedatabase.
Youshouldalsoconsiderusingtheblockifyouwanttoworkwithdatausingclient-sidequeryingmechanismssuchasLanguageIntegratedQuery(LINQ).Itcontainssupportfortheseprogrammingtechniquesbyexposingmethodsthatreturndataassequencesofobjects.
AthirdreasonforusingtheDataAccessApplicationBlockisitscapabilitytoabstractthedatabasetype.Thismakesiteasiertochangeyourapplicationtouseadifferenttypeofdatabaseifrequired,althoughsomeofthemoreadvanceddataaccessmethodsdorelyonthespecificcapabilitiesoftheunderlyingADO.NETDataProvider.
![Page 442: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/442.jpg)
ScenariosfortheDataAccessApplicationBlock
![Page 443: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/443.jpg)
BenefitsoftheDataAccessApplicationBlock
![Page 444: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/444.jpg)
LimitationsoftheDataAccessApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 445: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/445.jpg)
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheDataAccessApplicationBlock
ThissectiondescribeshowyoucanusetheDataAccessApplicationBlocktodevelopapplications.Itfirstexplainshowtoconfiguretheapplicationblockandincorporateitintoyourapplications.Next,itexplainshowtousetheapplicationblockforspecificscenarios,suchasretrievingasingleitemorusingaDataSetobjecttoretrievemultiplerows.Lastly,itprovidesmoreinformationabouttopicssuchasconnectionmanagement,parameterhandling,andhandlingexceptions.
Thissectionassumesthatyouareusingtheapplicationblockinitsoriginalstate,withoutextendingit.(Tolearnhowtoaddfunctionality,seeExtendingandModifyingtheDataAccessApplicationBlock.)Thissectionincludesthefollowingtopics:
EnteringConfigurationInformationAddingApplicationCodeCreatingaDatabaseObjectCreatingaDbCommandObjectManagingConnectionsUsingtheTransactionScopeClassUsingtheAsynchronousDataAccessMethodsReturningDataasObjectsforClientSideQueryingCreatingPortableDatabaseApplicationsHandlingExceptionsHandlingParameters
Allapplicationblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompileit.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Note:TheDataAccessBlockcannotbeusedinapplicationsthattargetthe.NETFramework4.0ClientProfile.Itcanonlybeusedinapplicationsthattargetthefull.NETFramework4.0profile.Forinformationaboutprofilesinthe
![Page 446: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/446.jpg)
.NETFramework4.0,see.NETFrameworkClientProfileonMSDN.Forinformationaboutchangingthetargetedprofile,seeHowto:TargetaSpecific.NETFrameworkVersionorProfileonMSDN.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 447: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/447.jpg)
MicrosoftEnterpriseLibrary5.0
EnteringConfigurationInformation
ThefollowingproceduresdescribehowtoconfiguretheDataAccessApplicationBlock.PropertiesassociatedwiththenodesappearintherightpaneoftheConfigurationConsoleorthePropertieswindowoftheVisualStudio®ConfigurationEditor.FordetailsoftheschemafortheDataAccessApplicationBlockconfiguration,seeSourceSchemafortheDataAccessApplicationBlock.Youcanalsoconfiguretheblockincodebyusinganalternateconfigurationsource.Formoreinformation,seeAdvancedConfigurationScenariosandUsingtheFluentConfigurationAPI.
ToaddtheDataAccessApplicationBlock1. Opentheconfigurationfile.Formoreinformation,seeConfiguring
EnterpriseLibrary.2. OpentheBlocksmenuandthenclickAddDataSettings.3. TheconfigurationtoolautomaticallyaddstheDatabaseSettings
sectionwithdefaultsettings.ClickthepropertiesexpanderchevronintheDatabaseSettingssectiontoviewthesettingsforthissection.
Thenextprocedureexplainshowtoconfigureaninstanceofthedefaultdatabasethatisaddedautomaticallytotheconfiguration.ThisinstanceisusediftheapplicationresolvesaDatabasewithnoinstancename.
Toconfigurethedefaultdatabase1. IntheDatabaseInstancespane,clicktheexpanderarrowforthe
ConnectionStringsection.
2. (Optional)SettheNamepropertybytypinganewname.ThedefaultnameisConnectionString.
3. UsetheDatabaseProviderpropertytochangetheprovidernameas
![Page 448: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/448.jpg)
required.Enterthenameoftheproviderorselectitfromthedrop-downlist.ThedefaultprovidernameisSystem.Data.SqlClient.Youcanchooseadifferentproviderifyouwish,suchasSystem.Data.OleDb.TheDatabaseProviderpropertymustbeaprovidernamespecifiedinaDBProviderFactoryclass.
4. Clicktheellipses(...)buttonintheConnectionStringpropertytoshowtheconnectionstringinapop-upwindow.Edititasrequired.
Thenextprocedureexplainshowtocreateadditionaldatabaseinstancesforotherdatabases.
Toconfigureadditionaldatabaseinstances1. ClicktheplussigniconintheDatabaseInstancespaneandthenclick
AddDatabasetoaddanewconnectionstringsection.
2. (Optional)SettheNamepropertybytypinganewname.Thisisthenameyouwillusetorefertothedatabase.
3. IntheDatabaseProviderpropertysection,enterthenameofthedatabaseproviderorselectitfromthedrop-downlist.TheDatabaseProviderpropertymustbeaprovidernamespecifiedinaDbProviderFactoryclass.IfyouareusingtheVisualStudiointegratedconfigurationeditorandyoudonotseetheprovidertypeyourequireinthelist,youmustaddareferencetotheassemblycontainingthe
![Page 449: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/449.jpg)
providertoyourproject.4. Clicktheellipses(...)buttonintheConnectionStringpropertyto
showtheconnectionstringinapop-upwindow.Typetheconnectionstringthatthisdatabasewilluse.Forexample,thefollowingconnectionstringspecifiesthedatabasenamedCorpData1ontheSQLServerinstancenamedDBSERVER1usingintegratedWindows®security:
Server=DBSERVER1;InitialCatalog=CorpData1;IntegratedSecurity=SSPI
ThenextproceduredescribeshowtochangewhichofthecurrentlyconfigureddatabasesisthedefaultthatwillbeusediftheapplicationresolvesaDatabasewithnoinstancename.
Tochangethedefaultdatabase1. ClickthepropertiesexpanderchevronintheDatabaseSettingssection
toviewthesettingsforthissectionifitisnotalreadyopen.2. Selectthedatabasethatyouwanttouseasthedefaultinthedrop-down
listfortheDefaultDatabaseInstanceproperty.
ThenextproceduredescribeshowtoconfigureaSQLServerCEdatabase.Thesestepsareappropriateifyourapplicationalwaysusesasinglefilethatyounameduringconfiguration.FormoreinformationaboutSQLServerCE,seeCreatingaDatabaseObject.
ToconfigureSQLServerCE1. ClicktheplussigniconintheCustomDatabasespaneandthenclick
AddCustomDatabaseProvider.2. SettheNamepropertyofthecustomdatabasebytypinganewname.
ThisnameisusedtolinktheSQLServerCEdatabaseprovidertotheconnectionstringyouwilldefineforit.
3. IntheTypeproperty,clicktheellipses(...)button,fullyexpandtheMicrosoft.Practices.EnterpriseLibrary.Data.SqlCenode,andselectSqlCeDatabase.ThenclickOK.
4. ClicktheplussigniconintheDatabaseInstancespaneandthenclickAddDatabaseConnectionString.Thisaddsanewconnectionstringtotheconfiguration,whichyouwillusetospecifytheconnectionstring
![Page 450: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/450.jpg)
CopyCode
fortheSQLServerCEdatabase.Alternatively,youcanconfigurethedefaultConnectionStringitemthattheconfigurationtooladdsifyoudonotrequireanyotherconnectionstringsinyourconfiguration.
5. (Optional)SettheNamepropertyoftheconnectionstringitembytypinganewname.Thisisthenameyouwillusetorefertothedatabaseinyourcode.
6. Clicktheellipses(...)buttonintheConnectionStringpropertytoshowtheconnectionstringinapop-upwindow.EntertheappropriatevaluefortheConnectionStringproperty;forexample:
DataSource='C:\MyApp\MyDatabase.sdf'
Note:TheSQLCEdatabaseiscreatedbytheEnterpriseLibrarySQLDatabaseprovider,whichdoesnotenforcepasswordprotectionorencryptiononthedatabaseduringcreation.Toensuresecurityofyorudata,youshouldconsidersettingtheconnectionstringtoprotectthefileandcreateitwiththecorrectpermissions,andencryptthefile.FormoreinformationseeSqlCEConnectionConnectionStringPropertyonMSDN.
7. Thefollowingexampleenablesencryptiononthedatabase:
"DataSource=MyData.sdf;EncryptDatabase=True;Password=myPassword;FileMode=sharedread;PersistSecurityInfo=False;"
8. SettheDatabaseProviderpropertyofyourSQLServerCEconnectionstringitemtothenameyouenteredforthecustomdatabaseproviderinstep2.ThefollowingscreenshotshowsdetailsoftheconfigurationforaSQLServerCEdatabaseintheconfigurationtools.
![Page 451: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/451.jpg)
9. ForinformationonusingSQLServerCE,seethesection"UsingSQLServerCE"inthetopicCreatingaDatabaseObject.
ThenextproceduredescribeshowtoaddOraclepackages.AnOraclepackageservesasawaytogroupstoredproceduresintocommongroups,typicallybasedontheirfunctionality.WhenanapplicationcallsanOraclestoredprocedurelocatedinapackage,thecodemustprefixthestoredprocedurenamewiththepackagename.Forexample,tocallaprocedurenamedGetEmployeeNamethatisinapackagenamedEmployee_pkg,youwouldcallEmployee_pkg.GetEmployeeName.
IncorporatingthiscodeintotheapplicationmakesitlessportablebecausethissyntaxisspecifictoOracle.Instead,theDataAccessApplicationBlockcanprefixthestoredprocedurewiththepackagename.Thismeansyourclientcodedoesnotneedtospecifythepackagenametocallastoredprocedure.Todothis,theapplicationblockusesinformationintheconfigurationfile.TheOraclePackagenodestoresaname/prefixpair.Thenameisthenameofthe
![Page 452: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/452.jpg)
package.Theprefixisastringthatisassociatedwiththepackage.Allstoredproceduresthatstartwiththatprefixareassumedtobeintheassociatedpackage.
Whentheapplicationcallsastoredprocedure,theDataAccessApplicationBlockcheckstoseeifitbeginswithanyoftheprefixesintheconfigurationfile.Ifitdoes,theapplicationblockprefixesthestoredprocedurewiththeassociatedpackagename.(Thefirstmatchitfindsistheonetheapplicationblockuses.)Ifyouspecifyanasterisk("*")astheprefix,theassociatedpackageisusedforallstoredprocedurecalls.
ToconfigureanOraclepackage1. ClicktheplussigniconintheOracleConnectionspane,andclick
AddOracleConnection.2. AnOraclePackagesforOracleConnectionsectionisaddedtothe
OracleConnectionspaneanditspropertiesaredisplayed.3. (Optional)SettheNamepropertybytypinganewname.4. ClicktheplussigniconinthePackagesrowtoaddanewpackage.
5. ChangetheNamepropertybyenteringthenameoftheOraclepackage.ThedefaultnameisPackage.
6. EnteravalueforthePrefixproperty.
Note:TheOracleClientdataproviderisdeprecatedinversion4.0ofthe.NETFramework,althoughitisstillsupportedbytheEnterpriseLibrary5.0.Forfuturedevelopment,considerchoosingadifferentOracledriver,suchasthatavailablefromtheEnterpriseLibraryContribsite.
Thenextproceduredescribeshowtoaddcustomprovidermappingsby
![Page 453: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/453.jpg)
associatingaproviderwiththefullyqualifiednameofadatabase.
Toconfigureacustomprovider1. ClicktheplussigniconintheCustomDatabasespane,andthenclick
onAddCustomDatabaseProvider.2. (Optional)SettheNamepropertybytypinganewnameorselectit
fromthedrop-downlist.ThedefaultprovidernameisCustomDatabaseProvider.
3. IntheTypepropertytextbox,clicktheellipsisbutton(…)andusethetypeselectortoselectthefullyqualifiednameoftheEnterpriseLibrarydatabasetype.Iftheproviderisregisteredintheglobalassemblycache(GAC),clicktheAddfromGACbuttontolocateit.IfyouareusingtheVisualStudiointegratedconfigurationeditorandyoudonotseetheprovidertypeyourequireinthelist,youmustaddareferencetotheassemblycontainingtheprovidertoyourproject.
![Page 454: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/454.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 455: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/455.jpg)
MicrosoftEnterpriseLibrary5.0
SourceSchemafortheDataAccessApplicationBlock
ThistopicliststheXMLelementsandattributesusedtoconfiguretheDataAccessApplicationBlock.YoucanmanuallyedittheXMLdata,buttheEnterpriseLibraryconfigurationtoolsgreatlysimplifythistask.IfyouchoosetomanuallyedittheXML,usetheschemainformationcontainedinthistopic.
Theconfigurationfilehasthefollowingsection-handlerdeclaration.XML
<configSections>
<sectionname="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data"/>
<sectionname="oracleConnectionSettings"
type="Microsoft.Practices.EnterpriseLibrary.Data.Oracle.Configuration.OracleConnectionSettings,
Microsoft.Practices.EnterpriseLibrary.Data"/>
</configSections>
Thesection-handlerdeclarationcontainsthenameoftheconfigurationsettingssectionsandthenamesofthesection-handlerclassesthatprocessconfigurationdatainthatsection.ThenameofthefirstconfigurationsettingssectionisdataConfiguration.Thenameofthesection-handlerclassisDatabaseSettings(intheMicrosoft.Practices.EnterpriseLibrary.Data.Configurationnamespace).
ThenameofthesecondconfigurationsettingssectionisoracleConnectionSettings.Thenameofthesection-handlerclassisOracleConnectionSettings(intheMicrosoft.Practices.EnterpriseLibrary.Data.Oracle.Configurationnamespace).
![Page 456: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/456.jpg)
connectionStringsElement
![Page 457: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/457.jpg)
dataConfigurationElement
![Page 458: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/458.jpg)
providerMappingsChildElement
![Page 459: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/459.jpg)
oracleConnectionSettings
![Page 460: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/460.jpg)
packagesChildElement
![Page 461: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/461.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 462: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/462.jpg)
CopyCode
CopyCode
MicrosoftEnterpriseLibrary5.0
AddingApplicationCode
TheDataAccessApplicationBlockisdesignedtosupportthemostcommonscenariosforaccessingadatabase.Whenyouaddyourapplicationcode,refertothescenariosintheKeyScenariossectionandselecttheonesthatbestmatchyoursituation.Usethecodethataccompaniesthescenarioas-isoradaptitasnecessary.
First,youmustprepareyourapplicationtousetheDataAccessApplicationBlock.Afteryoudothat,youcancreatetheDatabaseobjectandcalltheappropriatemethodoverloads.
Toprepareyourapplication1. AddareferencetotheDataAccessApplicationBlockassembly.In
VisualStudio,right-clickyourprojectnodeinSolutionExplorer,andthenclickAddReference.ClicktheBrowsetab,andthennavigatetothelocationoftheMicrosoft.Practices.EnterpriseLibrary.Data.dllassembly.Selecttheassembly,andthenclickOKtoaddthereference.
2. Followingthesameprocedure,addreferencestothefollowingassemblies:
Microsoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.Unity.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.Unity.Interception.dll.
3. (Optional)TouseelementsfromDataAccessApplicationBlockwithoutfullyqualifyingtheelementreference,youcanaddthefollowingusingstatement(C#)orImportsstatement(VisualBasic®)tothetopofyoursourcecodefile.C#
usingMicrosoft.Practices.EnterpriseLibrary.Data;
usingSystem.Data;
VisualBasic
![Page 463: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/463.jpg)
ImportsMicrosoft.Practices.EnterpriseLibrary.Data
ImportsSystem.Data
Note:ForVisualBasicprojects,youcanusetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer.OntheProjectmenu,clickProperties.WhentheProjectDesignerappears,clicktheReferencestab.
ForinformationonhowtocreateaDatabaseobjectandadviceonusingtheDatabasetypes,seeCreatingaDatabaseObject.
Forinformationaboutthekeyscenariosforusingtheblock,seeKeyScenarios.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 464: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/464.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingaDatabaseObject
AlldataaccessmethodsareexecutedagainstaDatabaseobject.YoucanusetheEnterpriseLibrarycontainertocreateaDatabaseobject.ThespecifictypeofDatabaseobjectitreturnsisdeterminedbytheapplicationconfigurationinformation.Bychangingthedefaultconfiguration,theunmodifiedapplicationcanberunagainstdifferentdatabases.Theconnectionstringinformationforeachdatabaseyoudefineisstoredinthe<connectionStrings>sectionintheapplicationconfigurationfile.
Thistopicincludesthefollowingsectionsthatdescribehowtocreateinstancesofdifferenttypesofdatabases,andsomethingsyoumustconsiderwhenworkingwithspecifictypesofdatabases:
CreatingaDefaultDatabaseInstanceCreatingaNamedDatabaseInstanceCreatingaSpecificDatabaseTypeCreatingaDatabaseInstanceDirectlyCreatingaGenericDatabaseInstanceWritingCodetoUsetheDatabaseClassesUsingSQLServerCEUsingOraclewiththeTransactionScopeClassUsingtheOracleDataReaderWrapperClass
![Page 465: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/465.jpg)
CreatingaDefaultDatabaseInstance
![Page 466: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/466.jpg)
CreatingaNamedDatabaseInstance
![Page 467: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/467.jpg)
CreatingaSpecificDatabaseType
![Page 468: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/468.jpg)
CreatingaDatabaseInstanceDirectly
![Page 469: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/469.jpg)
CreatingaGenericDatabaseInstance
![Page 470: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/470.jpg)
WritingCodetoUsetheDatabaseClasses
![Page 471: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/471.jpg)
UsingSQLServerCE
![Page 472: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/472.jpg)
UsingOraclewiththeTransactionScopeClass
![Page 473: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/473.jpg)
UsingtheOracleDataReaderWrapperClassToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 474: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/474.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingaDbCommandObject
TheDataAccessApplicationBlockprovidesaconsistentwaytoretrieveADO.NETDbCommandobjects.ThedataaccessmethodsoftheapplicationblockincludeoverloadsthatacceptaDbCommandobject.IfyouusetheoverloadswithDbCommandobjects,youhavemorecontrolwhenyoucallstoredprocedures.Forexample,ifyouuseaDbCommandobject,youcanhaveastoredprocedurethatreturnsseveralresultsintheoutputparameters.Inaddition,aDbCommandobjectallowsyoutospecifythestoredprocedure'stimeoutvalue.
ThemethodsthatcreateDbCommandobjectsareseparatedintotwotypes:Methodsthatrepresentstoredprocedurecalls(forexample,GetCustomers)MethodsthatrepresentSQLtextcommands(forexample,SelectCustomerID,FullnameFromCustomers)
ThemethodyoucalltoretrieveaDbCommandobjectisdeterminedbywhetheryouwanttoexecuteinlineSQLorcallastoredprocedure.ThemethodthatcreatesaDbCommandobjectforastoredprocedurealsoprovidesparametercaching.Formoreinformationaboutparametercaching,seeHandlingParameters.
AllDbCommandobjectsarecreatedusingmethodsontheDatabaseclass.Thesemethodsarethefollowing:
GetStoredProcCommand.Thismethodisforstoredprocedurescommands.GetSqlStringCommand.ThismethodisforSQLtextcommands.
BothmethodsreturnaDbCommandobject.
Note:SQLServerCEdoesnotsupportstoredprocedures.Instead,useinlineSQLstatements.Formoreinformation,seethesection"UsingSQLServerCE"inCreatingaDatabaseObject.
![Page 475: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/475.jpg)
DbCommandObjectsforSQLStatements
![Page 476: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/476.jpg)
DbCommandObjectsforStoredProceduresToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 477: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/477.jpg)
CopyCode
MicrosoftEnterpriseLibrary5.0
ManagingConnections
Databaseconnectionsarealimitedresource,andpropermanagementofthemisessentialforscalableapplications.Itisgoodpracticetokeepconnectionsopenonlyaslongastheyareneededandtoclosethemassoonaspractical.Bydesign,mostoftheDatabaseclassmethodshandletheopeningandclosingofconnectionstothedatabaseoneachcall.Therefore,theapplicationcodedoesnotneedtoincludecodeformanagingconnections.(Bydefault,andforperformancereasons,ADO.NETreturnsconnectionstotheconnectionpoolwithoutclosingthem.Therefore,youdonotneedtocacheyourDatabaseobjects.)
Forexample,theExecuteDataSetmethodreturnsaDataSetobjectthatcontainsallthedata.Thisgivesyouyourownlocalcopy.ThecalltoExecuteDataSetopensaconnection,populatesaDataSet,andclosestheconnectionbeforereturningtheresult.
ThefollowingcodedemonstratestheuseoftheExecuteDataSetmethod.ItassumesthatyouhaveresolvedtheDatabaseclassyourequireandstoredareferenceinthevariablenameddb.
Formoreinformationoninstantiatingobjects,seeCreatingandReferencingEnterpriseLibraryObjects.C#
stringsql="SelectProductID,ProductNameFromProducts";
DbCommandcmd=db.GetSqlStringCommand(sql);
//Noneedtoopentheconnection;justmakethecall.
DataSetcustomerDataSet=db.ExecuteDataSet(cmd);
VisualBasic
DimsqlAsString="SelectProductID,ProductNameFromProducts"
DimcmdAsDbCommand=db.GetSqlStringCommand(sql)
![Page 478: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/478.jpg)
'Noneedtoopentheconnection;justmakethecall.
DimcustomerDataSetAsDataSet=db.ExecuteDataSet(cmd)
However,thereareothercaseswhereitisunclearwhentoclosetheconnection.AnexampleistheExecuteReadermethod.ThismethodreturnsanobjectthatimplementstheIDataReaderinterface.TheDatabasebaseclasshasadefaultimplementationthatreturnsaDbDataReaderobject.DbDataReaderobjectsaredesignedtoreadspecificportionsofthedataasneeded,whichrequiresanopenconnection.Inotherwords,itisunknownwhentheapplicationnolongerneedstheDbDataReader.
IftheDataAccessApplicationBlockmethodsclosetheconnectionbeforereturningtheDbDataReader,theDbDataReaderbecomesuselesstotheclientcode.Instead,theDbDataReadermethodsindicatetotheunderlyingADO.NETcalltoautomaticallyclosetheconnectionwhentheDbDataReaderisdisposed.
Note:IfyoufailtoclosetheDbDataReader,youcancauserandomandhard-to-finderrorsinyourcode—particularlywhenyouareoperatingunderanimplicittransactioncreatedwithinaTransactionScopecontext.YoushouldalwaysensurethatyourapplicationclosestheDbDataReaderinatimelyfashion,eitherbyexplicitlyclosingthereaderusingtheDbDataReader.ClosemethodorbyforcingthedisposaloftheDbDataReader,whichresultsintheClosemethodbeingcalled.
ThefollowingcodedemonstratesacalltotheExecuteReadermethod.Theusingstatement(UsinginVisualBasic)ensuresthattheDbDataReaderobjectisdisposed,whichclosestheDbDataReaderobject.ItassumesthatyouhaveresolvedtheDatabaseclassyourequireandstoredareferenceinthevariablenameddb.
Formoreinformationoninstantiatingobjects,seeCreatingandReferencingEnterpriseLibraryObjects.C#
![Page 479: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/479.jpg)
DbCommandcmd=db.GetSqlStringCommand("SelectName,AddressFromCustomers");
using(IDataReaderreader=db.ExecuteReader(cmd))
{
//Processresults
}
VisualBasic
DimcmdAsDbCommand=db.GetSqlStringCommand("SelectName,AddressFromCustomers")
UsingreaderAsIDataReader=db.ExecuteReader(cmd)
'Processresults
EndUsing
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 480: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/480.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheTransactionScopeClass
SomeoftheDatabaseclassmethodstakeadvantageofthe.NETFrameworkTransactionScopeclass.Thisclassautomaticallyenlistsdatabasecallsintoanambienttransaction.Thisisusefulforenlistingbusinessobjectsinatransactionwithoutpassingatransactiontothosebusinessobjects.HereisthebasicmodelforusingtheTransactionScopeclass.ItassumesthatyouhaveresolvedtheDatabaseclassyourequireandstoredareferenceinthevariablenameddb.
FormoreinformationoninstantiatingobjectsseeCreatingandReferencingEnterpriseLibraryObjects.C#
using(TransactionScopescope=newTransactionScope(TransactionScopeOption.RequiresNew))
{
intdRows=db.ExecuteNonQuery(CommandType.Text,insertString);
dRows=db.ExecuteNonQuery(CommandType.Text,insertString2);
}
VisualBasic
UsingscopeAsNewTransactionScope(TransactionScopeOption.RequiresNew)
DimdRowsAsInteger=db.ExecuteNonQuery(CommandType.Text,insertString)
dRows=db.ExecuteNonQuery(CommandType.Text,insertString2)
EndUsing
ThetwoExecuteNonQuerymethodsinserttherowswithinthetransactionthatyoudefinewhenyoucreateanewTransactionScopeinstance.
TheTransactionScopeclasscreatesalocal,lightweighttransaction.Itassumesthatyouwilluseasingleconnectionforallofthedatabasecallsthatoccurwithinthetransaction.Thismeansthat,insteadofpassingtheDbTransactioninstance,yousimplypasstheconnection,andthe.NETFrameworkautomaticallysetsthetransactionforeachcommandthatyouexecute.
EnterpriseLibrary,ontheotherhand,normallyopensandclosesaconnection
![Page 481: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/481.jpg)
foreachrequest.ThisapproachisincompatiblewiththewaytheTransactionScopeclassworks.Iftherearemultipleconnections,theTransactionScopeclassconsidersthetransactiontobeadistributedtransaction.Distributedtransactionshaveasignificantperformanceandresourceoverheadcomparedwithalocaltransaction.
Toavoidthis,theDatabaseclassmethods,suchasExecuteDataSet,recognizewhenaTransactionScopeinstanceisactiveandtheyenlistdatabasecallsinthistransaction.IfatransactioniscurrentlyactiveasaresultofusingaTransactionScopeinstance,theDatabaseclassmethodsuseasingleconnection.
Inparticular,theGetOpenConnectionmethodreplacestheOpenConnectionmethodwithintheDatabasemethods.TheGetOpenConnectionmethodreturnsaconnectioninsideawrapper.Themethoddisposesthewrapperifthereisnotransactioninprogress.However,whenatransactionisinprogress,themethodkeepstheconnectionopen.
Note:Multiplethreadssharingthesametransactioninatransactionscopewillcausethefollowingexception:"Transactioncontextinusebyanothersession."
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 482: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/482.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheAsynchronousDataAccessMethods
Oneofthemostcommonfactorsthatcanaffectperformanceinapplicationsisaccessingadatabase,andmostsystemdesignsaimtominimizedatabaseroundtrips.Simplycallingacrossanetworktoadatabasecancausesignificantdelays,andtheadditionaldelaywhilethedatabaseprocessesaquerycanbeparticularlytroublesomeininteractiveapplicationswherethedelaycancausetheUItobecomeunresponsive.Toresolvethis,youmayconsiderusingasynchronousmethodstoaccessyourdatabase.
TheDataAccessApplicationBlockcontainsversionsoffourofthedataaccessmethodsthatyoucanexecuteasynchronously.ThesemethodsrelyonthefeaturesoftheunderlyingADO.NETdataprovider,andarethereforeavailableonlyfortheSqlDatabaseimplementationoftheDatabaseclassinthisrelease.TheDatabaseclassexposesamethodnamedSupportsAsyncthateachdatabase-specificclass(suchasSqlDatabase,OracleDatabase,andSqlCeDatabase)implementstoreturntrueorfalse.Thethreepairsofasynchronousmethodsavailablearethefollowing:
BeginExecuteReaderandEndExecuteReader.ThesemethodsareusedtoobtainaDataReaderpopulatedwithdatafromthedatabase.BeginExecuteScalarandEndExecuteScalar.Thesemethodsareusedtoobtainasinglevaluefromthedatabase.BeginExecuteNonQueryandEndExecuteNonQuery.Thesemethodsareusedtoexecuteaquerythatdoesnotreturndata,butreturnsonlyacountofthenumberofrowsaffected.
Inaddition,whenusingSqlDatabasedirectly,anadditionalpairofasynchronousmethodsisavailable:
BeginExecuteXmlReaderandEndExecuteXmlReader.ThesemethodsareusedtoobtainanXmlReaderpopulatedwithdatafromthedatabase.
TheBeginandEndversionsofthemethodsoperateinthesamewayasthoseavailablewhenyoucodedirectlyagainsttheADO.NETprovider.WhenusingtheDataAccessApplicationBlock,youpasstothemethodsthesameparametersasforthenon-asynchronousversions,suchasaDbCommandand(optionally)atransactionreference.ThemethodsreturnaninstanceoftheIAsyncResultinterface,whichyouthenuseastheparameterinacalltothe
![Page 483: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/483.jpg)
Endversionofthemethodtoobtaintheresult.Yourcodewaitsuntilthemethodcompletes.However,youcanuseanarrayofthestandardWindowsWaitHandleclasstostartmultipledataaccessoperations,andthecodewillreturnwhentheyallcompleteortimeout.
Ifyouwanttoexecutecodeinyourapplicationwhilethedataaccesscallisexecuting,youcanusealambdaexpressionoraseparatecallbackthatisexecutedwhendataaccessiscomplete.Ifyouuseaseparatecallback,youpassareferencetoyourcallbackmethodtotheBeginmethod,andoptionallyanobjectcontainingstateinformationthatyouwanttomakeavailableinthecallbackmethod.AcommonuseofthisobjectistopassareferencetotheDatabaseobjectsothatyoucancalltheappropriateEndmethodinsidethecallbackhandler.Ifyouusealambdaexpression,itwillhaveaccesstotheobjects(suchastheDatabaseinstance)thatyouuseinthedataaccesscode.
AsthemethodsforperformingasynchronousexecutionmatchthoseavailablefortheADO.NETSqlClientclass,thefullrangeofoptionsandapproachestoperformingasynchronousdataaccessarenotincludedinthistopic.Formoreinformation,seeAsynchronousCommandExecutioninADO.NET2.0.
![Page 484: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/484.jpg)
AsynchronousAccessorExecution
![Page 485: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/485.jpg)
TipsforUsingtheAsynchronousDataAccessMethodsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 486: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/486.jpg)
MicrosoftEnterpriseLibrary5.0
ReturningDataasObjectsforClientSideQuerying
Developersoftenwanttoretrievedatainaformatthatbettermatchesthereal-worldobjectsthatthedatarepresents,ratherthanintherowsandcolumnsformatofaDataReaderorDataSet.ThisistypicallythecasewhenimplementingcommondesignpatternssuchasDomainModel,TableModule,andRepository.
TheDataAccessApplicationBlockincludessupportforthisscenariothroughaclasscalledanaccessor.Accessorsacceptinformationthatisrequiredtoextractthedata,andmappingsthatindicatehowtheinputparameterscorrespondtotheparametersoftheunderlyingquery.Theyuseoutputmappingsthatdefinehowthereturnedcolumnsmaptothepropertiesoftheobjectsthedeveloperwantstoworkwith,andreturnasequenceofobjectsofthespecifiedtype.Thefollowingschematicshowsthehighlevelprocesswhenusinganaccessortoretrievedataasanenumerablesequenceofobjects.
YoucanexecutebothstoredproceduresandSQLstatementsusingtheaccessorapproach.TheblockincludestheSprocAccessorclassforstoredprocedures
![Page 487: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/487.jpg)
andtheSqlStringAccessorclassforexecutingSQLstatements.Accessorsalsoprovidemethodsforasynchronousdataretrievalwherethedatabaseyouareusingsupportsasynchronousqueryexecution.
Themappingmechanismisflexibleandextensible.ForstoredproceduresexecutedagainstSQLServerandOracledatabases,theaccessorwillattempttoresolvetheparametersautomaticallyifyoudonotspecifyaparametermapperthatdefinesthecorrelation.However,defaultparametermappingisnotavailablewhenusingSQLstatements,orforotherdatabasesandproviders.Inthesecases,youmustspecifyacustomparametermapperthatcanresolvetheparameters.
Note:Keepinmindthatcreatingstoredprocedureaccessorswiththedefaultmappermayberesourceintensiveandaffectperformance.Considercachingtheaccessorand/orthemapper.
Whenyouexecuteanaccessor,youcanprovideanoutputmappingthatindicateshowtheaccessorshouldmapthevaluesreturnedfromthedatabasetothepropertiesoftheobjectsitreturnstothecaller.Ifyoudonotspecifyanoutputmapper,theblockusesadefaultmapbuilderclassthatmapsthecolumnnamesofthereturneddatatopropertiesoftheobjectsitcreates.Alternatively,youcancreateacustommappingtospecifythecorrelationbetweencolumnsintherowsetandthepropertiesoftheobjects.
TheaccessorreturnsdataasasequenceofobjectsintheformIEnumerable<TResult>,whereeachobjectrepresentsonerowofdatainthedatasourceandexposespropertiesthatmaptothecolumnsineachrow.Youcanhandletheresultsinyourcodeasobjectsthatarepartofyourdatamodel,orquerythemusingclient-sidetechniquessuchasLanguageIntegratedQuery(LINQ).
Thefollowingshowsasimpleexampleofexecutingastoredprocedurethattakesnoparametersandthenqueryingtheresultsreturnedfromtheaccessor.ThecodeassumesyouhavedefinedtheCustomerclasselsewhere,andyouhaveresolvedaninstanceoftheDatabaseclassyouwanttouseandstoreditinthevariablenameddb.
![Page 488: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/488.jpg)
C#
//Createanoutputrowmapperthatmapsallpropertiesbasedonthecolumnnames
IRowMapper<Customer>mapper=MapBuilder<Customer>.BuildAllProperties();
//Createastoredprocedureaccessorthatusesthisoutputmapper
varaccessor=db.CreateSprocAccessor("TopTenCustomers",mapper);
//Executetheaccessortoobtaintheresults
varcustomerData=accessor.Execute();
//Performaclient-sidequeryonthereturneddata
varresults=fromcustomerincustomerData
wherecustomer.State=="WA"
orderbycustomer.Name
selectnew{Name=customer.Name};
//Displaytheresults
foreach(varcustomerinresults)
{
Console.WriteLine("{0}isatopcustomerinWashingtonState",customer);
}
VisualBasic
'Createanoutputrowmapperthatmapsallpropertiesbasedonthecolumnnames
DimmapperAsIRowMapper(OfCustomer)=MapBuilder(OfCustomer).BuildAllProperties()
'Createastoredprocedureaccessorthatusesthisoutputmapper
Dimaccessor=db.CreateSprocAccessor("TopTenCustomers",mapper)
'Executetheaccessortoobtaintheresults
DimcustomerData=accessor.Execute()
'Performaclient-sidequeryonthereturneddata
Dimresults=FromcustomerIncustomerData_
Wherecustomer.State="WA"_
OrderBycustomer.Name_
![Page 489: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/489.jpg)
SelectName=customer.Name
'Displaytheresults
ForEachcustomerInresults
Console.WriteLine("{0}isatopcustomerinWashingtonState",customer)
Next
Therearealsomethodsthatallowyoutopassparametersoraparametermappertotheaccessor,andexecuteaquerywithoutcreatinganaccessordirectly.Formoreinformationaboutusingaccessorstoretrievedataasobjects,seethefollowingtopics:
DefiningParameterMappersBuildingOutputMappersCreatingandUsingAccessorsExecutingQuerieswithoutCreatinganAccessorExecutingAccessorQueriesAsynchronouslyAdditionalInformationforAccessorsandClient-sideQueries
Note:TheaccessorfeatureintheDataAccessApplicationBlockisnotanObject/RelationalMapping(OR/M)mechanism,andshouldnottobeconfusedwithLINQtoSQL,oranyotherimplementationthatperformsoptimizationofqueries.Itdoesnotprovidesupportforupdates,identitymaps,foreignkeys,joins,orautomaticSQLgeneration.Thetechniqueforclient-sidequeriesmorecloselyresemblesthatofLINQtoObjects.However,thereisnoassumptiononhowyouwill(orcan)usethereturnedobjectgraphinyourapplications.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 490: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/490.jpg)
MicrosoftEnterpriseLibrary5.0
DefiningParameterMappers
AparametermappertakesthesetofobjectsyouwanttopasstoaqueryandconvertseachoneintoaDbParameterobject.Theaccessorassignstheseparameterstothecommandobjectitusestoaccessthedatasource.Forinformationaboutusingparametermapperswithanaccessor,seeCreatingandUsingAccessorsandExecutingQuerieswithoutCreatinganAccessor.
TheDataAccessApplicationBlockincludesadefaultparametermappingmechanism.ThismechanismmapsvaluesyouprovideasqueryparameterstotheDbParameterinstancesthequerywillusewhenexecutingagainstthedatabase.
Note:ThedefaultparametermappingmechanismisonlyavailablefortheSqlDatabaseandOracleDatabaseclasses,orforcustomdatabaseclassesyoucreatewherethedatabasesupportsparameterdiscovery.TheDatabaseclassexposesaBooleanpropertynamedSupportsParemeterDiscoverythatyourcodecantest(notethat,forbackwardcompatibilityreasons,themisspellingofthisnameispreservedinthecurrentversion).Ifyouuseanyotherdatabaseprovider,youmustcreateasuitableimplementationoftheIParameterMapperinterfacethatassignstheparametervaluestotheDbCommand.Formoreinformation,seeCreatingCustomParameterMapperslaterinthistopic.
Thisdefaultmappingusesthepositionoftheparametersyouprovideintheobjectarray,andexecutestheADO.NETDeriveParametersmethodtodiscovertheparametersrequiredbytheprocedure.Itmapsyourparameter(0)tothefirstparameteroftheprocedure,parameter(1)tothesecondparameteroftheprocedure,andsoon.ItconvertstheCLRtypesyouspecifyintotheappropriatedatabasetypesforeachDbParameteritpopulates.
TheADO.NETDeriveParameterscallthatresolvesparametersforastoredprocedurerequiresaround-triptothedatabase.Theapplicationblockprovidesparameterinformationcachingtomitigatetheperformancehitthatthisincurs.
![Page 491: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/491.jpg)
Afterthefirstcalltoastoredprocedurethatrequiresparameterdiscovery,theinformationabouteachparameterissavedintheparametercache.Thismeansthatsubsequentcallstothesamestoredprocedurewillnotrequirearound-triptothedatabase.
![Page 492: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/492.jpg)
CreatingCustomParameterMappersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 493: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/493.jpg)
MicrosoftEnterpriseLibrary5.0
BuildingOutputMappers
Anoutputmappertakestheresultsetreturnedfromadatabase(intheformofrowsandcolumns)andconvertsthedataintoasequenceofobjects.Therearetwodifferenttypesofoutputmappersthatyoucanusetotransformthereturneddata.Rowmapperstransformeachrowintoanobject,sothattheaccessorcanreturnasequenceoftheseobjects.Resultsetmapperstaketheentireresultsetandgenerateacompleteobjectgraphthatrepresentstheresultsetasobjects.
Thefollowingsectionsofthistopicprovidemoreinformationaboutthedefaultmappingcapabilitiesandthetwotypesofoutputmapper:
UsingtheDefaultRowMapperDefiningCustomRowMappingsCreatingResultSetMappers
Forinformationaboutusingoutputmapperswithanaccessor,seeCreatingandUsingAccessorsandExecutingQuerieswithoutCreatinganAccessor.
![Page 494: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/494.jpg)
UsingtheDefaultRowMapper
![Page 495: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/495.jpg)
DefiningCustomRowMappings
![Page 496: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/496.jpg)
CreatingResultSetMappersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 497: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/497.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingandUsingAccessors
Accessorsexecutethequeryyouspecifyusingtheparametervaluesandaparametermapper(ifprovided),andtransformtheresultintoaseriesofobjectsusingtheoutputmapperyouspecify.YoucancreateanaccessorbycallingamethodonyourchosenimplementationoftheDatabaseclass,suchasSqlDatabaseorOracleDatabase,oryoucancreateanaccessordirectlyusingthenewoperatororthroughdependencyinjection.
Note:BecauseoftheoverheadassociatedwithsettingupAccessorsandtheirassociatedmappings,yougainimprovedperformancebycreatingtheaccessorinadvance,maintainingareferencetoit,andreusingtheinstance.Usingthistechniqueyouonlyincurthesetupcostonceinsteadofeverytimeyoucallthedatabase.
Thedifferencebetweenusingthedefaultmappersandprovidingyourownimplementationofthemapperinterfaces,IRowMapperandIResultSetMapper,isthatwhenprovidingyourownimplementationyoucangetbetterperformancethroughspecialcasecode,ordomoresophisticateddatatransformationsthanthedefaultcolumn-to-propertydirectmapping.Thecosthereisthetimetoimplementthatspecialcasecodeandthefuturemaintenanceburden.
TheDataAccessApplicationBlockprovidestwoaccessorsthatyoucanusetoretrievedataasobjects.Thefollowingsectionsofthistopicdescribeeachoneindetail:
StoredProcedureAccessorSQLStringAccessor
Seethefollowingtopicsformoreinformationaboutusingaccessorsinyourapplications:
DefiningParameterMappersBuildingOutputMappers
![Page 498: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/498.jpg)
ExecutingQuerieswithoutCreatinganAccessorExecutingAccessorQueriesAsynchronouslyAdditionalInformationforAccessorsandClient-sideQueries
![Page 499: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/499.jpg)
StoredProcedureAccessor
![Page 500: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/500.jpg)
SQLStringAccessor
![Page 501: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/501.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 502: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/502.jpg)
MicrosoftEnterpriseLibrary5.0
ExecutingQuerieswithoutCreatinganAccessor
Insteadofcreatinganaccessorfirst,andthenexecutingit,youcanusethemethodsoftheDatabaseclasstocreateanaccessorandexecuteitasoneoperation.YoucandothiswithboththeSprocAccessorandSqlStringAccessor.ThemaindifferencebetweenthisapproachandcallingtheExecutemethodexplicitlyonanexistingaccessoristhatyoumustalsopassanyrequiredparametersintotheExecuteSprocAccessormethod.Thefollowingsectionsshowthetechniqueforthetwotypesofaccessor:
StoredProcedureAccessorSQLStringAccessor
Seethefollowingtopicsformoreinformationaboutusingaccessorsinyourapplications:
DefiningParameterMappersBuildingOutputMappersCreatingandUsingAccessorsExecutingAccessorQueriesAsynchronouslyAdditionalInformationforAccessorsandClient-sideQueries
![Page 503: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/503.jpg)
StoredProcedureAccessor
![Page 504: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/504.jpg)
SQLStringAccessorToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 505: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/505.jpg)
MicrosoftEnterpriseLibrary5.0
ExecutingAccessorQueriesAsynchronously
Youcanexecuteaccessorsasynchronouslyifyouwish,inmuchthesamewasasyoucanexecutemanyoftheothermethodsoftheDataAccessApplicationBlock.However,thisisonlypossiblewheretheunderlyingdatabasesupportsasynchronousoperations(inotherwords,theDatabase.SupportsAsyncpropertyistrue).
TheSprocAccessorandSqlStringAccessorclassesexposetheBeginExecutemethod,whichtakesasparametersareferencetoacallbackmethodthatwillexecutewhentheoperationends,aparameterthatcontainsstateyouwanttopasstothecallbackmethod,andanobjectarraycontainingtheparametervaluestheaccessorwillusewhenitexecutesthequery.TypicallyyouwillpassareferencetotheaccessorastheasynchronousstateparametersothatyoucancalltheEndExecutemethodonitwithinthecallbackmethod.
TheaccessorsexposeonlyasingleoverloadoftheBeginExecutemethod.YoucancreatetheaccessorusinganyofthetechniquesdescribedinthetopicCreatingandUsingAccessors.
Whenthequeryoperationcompletes,thecodeinthecallbackhandlerexecutesandyoucanretrievetheaccessorandcalltheEndExecutemethodtoretrievetheIEnumerablesequenceastheresult.Thefollowingcodeshowsanexampleofusingasynchronousoperationswithanaccessor.Noticethattheconnectionstringspecifiesaconnectionthatsupportsasynchronousoperations.Inaddition,keepinmindthattheconnectionisnotcloseduntiltheentirelistisprocessed.YoumustforcecompleteevaluationoftheresultsequencetoextractallofthedatawhenyoucalltheEndExecutemethod.Forexample,calltheToListmethod,asshowninthefollowingcodeextract.C#
StringconnectionString
=@"server=(local);database=Northwind;IntegratedSecurity=true;AsynchronousProcessing=true";
SqlDatabasedb=newSqlDatabase(connectionString);
DbCommandcmd=db.GetStoredProcCommand("SomeProcedureName");
try
![Page 506: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/506.jpg)
{
//Createtheaccessor.Thisexampleusesthesimplestoverload.
varaccessor=db.CreateSprocAccessor<Customer>("TopTenCustomers");
//Executetheaccessorasynchronously,passinginthecallbackhandler,
//theexistingaccessorastheAsyncState,andtheparametervalues.
IAsyncResultasync=accessor.BeginExecute(MyEndExecuteCallback,accessor,2009,"WA");
}
catch
{
//...
//handleanyexecutioninitiationerrorshere
}
//================================================
//callbackhandlerthatexecuteswhencallcompletes
publicvoidMyEndExecuteCallback(IAsyncResultasync)
{
try
{
//obtaintheresultsfromtheaccessor
DataAccessoraccessor=async.AsyncStateasDataAccessor<Customer>;
varcustomers=accessor.EndExecute(async).ToList();
//...
//usetheresultshere
//...
}
catch
{
//...
//handleanyexecutioncompletionerrorshere
}
}
VisualBasic
DimconnectionStringAsString_
![Page 507: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/507.jpg)
="server=(local);database=Northwind;IntegratedSecurity=true;AsynchronousProcessing=true"
DimdbAsNewSqlDatabase(connectionString)
DimcmdAsDbCommand=db.GetStoredProcCommand("SomeProcedureName")
Try
'Createtheaccessor.Thisexampleusesthesimplestoverload.
Dimaccessor=db.CreateSprocAccessor(OfCustomer)("TopTenCustomers")
'Executetheaccessorasynchronously,passinginthecallbackhandler,
'theexistingaccessorastheAsyncState,andtheparametervalues.
DimasyncAsIAsyncResult_
=accessor.BeginExecute(AddressOfMyEndExecuteCallback,accessor,2009,"WA")
Catch
'...
'handleanyexecutioninitiationerrorshere
EndTry
'================================================
'callbackhandlerthatexecuteswhencallcompletes
PublicSubMyEndExecuteCallback(asyncAsIAsyncResult)
Try
'obtaintheresultsfromtheaccessor
DimaccessorAsDataAccessor=TryCast(async.AsyncState,DataAccessor(OfCustomer))
Dimcustomers=accessor.EndExecute(async).ToList()
'...
'usetheresultshere
'...
Catch
'...
'handleanyexecutioncompletionerrorshere
EndTry
EndSub
AnalternativeapproachtocodingthecallbackistousealambdafunctiondeclaredwithinthecalltotheBeginExecutemethodoftheAccessor.
![Page 508: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/508.jpg)
Note:Therearesomelimitationsonusingasynchronousdataoperations,andseveralissuesyoushouldbeawareof.Formoredetails,seeUsingtheAsynchronousDataAccessMethods.
Inaddition,whenyouexecuteanaccessorasynchronously,youcanonlyiterateovertheresultsetonce.Ifyouattempttoiterateoveritagain,theblockwillraiseanexception.Forthisreason,youmayneedtouseanapproachsuchastheToListmethodtoforcecompleteevaluationoftheresultsequence.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 509: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/509.jpg)
MicrosoftEnterpriseLibrary5.0
AdditionalInformationforAccessorsandClient-sideQueries
Thistopicdescribessomeadditionalfactorsandissuesrelatedtousingaccessorstoretrievedataasasequenceofobjects.Itcoversthefollowing:
CreatingAccessorsthroughDependencyInjectionAccessingandIteratingtheResultsSetQueryingtheResultsSetUsingLINQDeferredLoadingandMultipleIterationsoftheResultSet
![Page 510: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/510.jpg)
CreatingAccessorsthroughDependencyInjection
![Page 513: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/513.jpg)
DeferredLoadingandMultipleIterationsoftheResultSetToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 514: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/514.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingPortableDatabaseApplications
Thereareissuesthatyoumustconsiderifyourapplicationmustworkwithmultipledatabasetypes.
![Page 515: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/515.jpg)
WorkingwithOracleDatabases
![Page 516: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/516.jpg)
SuggestionsforCreatingPortableDatabaseApplicationsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 517: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/517.jpg)
MicrosoftEnterpriseLibrary5.0
HandlingExceptions
Strategiesforhandlingexceptionsareessentialinanyenterpriseapplication.ThefollowinginformationwillhelpyouincorporatetheDataAccessApplicationBlockintoyourapproachtomanagingexceptions:
Theapplicationblockusesconfigurationinformation,whichmayresultinconfiguration-relatedexceptions.TheDatabasemethodsusebothADO.NETandtheunderlyingdatabaseprovider.ExceptionsthrownbyADO.NETarecaughtbytheDataAccessApplicationBlockforinstrumentationpurposes,andthentheyarere-thrown.Adequatelyprocessinganexceptionoftenrequiresaccesstothespecificexceptiontype.YoucanincludeacatchstatementforaspecificdatabaseproviderexceptionsuchasSqlException.However,databaseprovider–specificexceptiontypesarenotportableacrossdifferentproviders.
IfyouuseExecuteReaderwithinatryblock,youshouldaddafinallystatementandclosethereturnedDataReaderobject,asshowninthefollowingexample.ItassumesthatyouhaveresolvedtheDatabaseclassyourequireandstoredareferenceinthevariablenameddb.Formoreinformationoninstantiatingobjects,seeCreatingandReferencingEnterpriseLibraryObjects.C#
DbCommandcmd=db.GetStoredProcCommand("GetProductsByCategory");
IDataReaderreader=null;
try
{
//...
reader=db.ExecuteReader(cmd);
}
catch(Exceptionex)
{
//Processexception
}
![Page 518: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/518.jpg)
finally
{
if(reader!=null)
reader.Close();
}
VisualBasic
DimcmdAsDbCommand=db.GetStoredProcCommand("GetProductsByCategory")
DimreaderAsIDataReader=Nothing
Try
'...
reader=db.ExecuteReader(cmd)
CatchexAsException
'Processexception
Finally
If(NotreaderIsNothing)Then
reader.Close()
EndIf
EndTry
Alternatively,youcanincludetheusingstatementtodisposeoftheDataReaderobject,whichcausesittoclose,asshowninthefollowingexample.C#
DbCommandcmd=db.GetStoredProcCommand("GetProductsByCategory");
using(IDataReaderreader=db.ExecuteReader(cmd))
{
//Processresults
}
VisualBasic
![Page 519: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/519.jpg)
DimcmdAsDbCommand=db.GetStoredProcCommand("GetProductsByCategory")
UsingreaderAsIDataReader=db.ExecuteReader(cmd)
'Processresults
EndUsing
Fordesignandimplementationguidelinesforexceptionmanagementin.NET,seetheDesignGuidelinesforExceptions.
![Page 520: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/520.jpg)
HandlingAsynchronousDataAccessExceptionsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 521: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/521.jpg)
MicrosoftEnterpriseLibrary5.0
HandlingParameters
Moststoredproceduresacceptparameterswhosevaluesareeitherusedasinputtothestoredprocedureoraresetduringoutput.AswithADO.NET,theDataAccessApplicationBlockallowsdeveloperstoexplicitlyspecifyalloftheattributesofaparameter.Theseattributescanincludedirection,datatype,andlength.Thisapproachisnamedexplicitparameterhandling.However,asaconvenience,youcanspecifyonlythevalueswhenusinginputparameters.Inthiscase,theapplicationblockwilllookupandsupplytheparameterattributes.Thisapproachisnamedparameterdiscovery.
![Page 522: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/522.jpg)
ExplicitParameterHandling
![Page 523: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/523.jpg)
UsingColumnValuesasParameterInputs
![Page 524: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/524.jpg)
ParameterDiscovery
![Page 525: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/525.jpg)
OptionalParametersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 526: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/526.jpg)
MicrosoftEnterpriseLibrary5.0
KeyScenarios
Thistopicdescribesthemostcommonsituationsdevelopersmustaddresswhenaccessingadatabase.Eachscenarioexplainsthetask,describesareal-worldsituationwheresuchataskmightarise,andincludescodedemonstratinghowtousetheDataAccessApplicationBlocktocompletethetask.Thescenariosareasfollows:
UsingaDbDataReadertoRetrieveMultipleRows.ThisscenarioillustrateshowyoucanusetheExecuteReadermethodtoretrievemultiplerowsofdatafromadatabasefordisplayintabulatedform—withoutexplicitlycachingthedata,usingaDataSetobjecttomanipulateit,orpassingittoothercomponentswithinyourapplication.Inotherwords,itillustrateshowtodisplaytheresultsasquicklyaspossible.UsingaDataSettoRetrieveMultipleRows.ThisscenarioillustrateshowyoucanusetheExecuteDataSetmethodtopassdatabetweenthecomponentsandthetiersofamulti-tierapplication.Thedataconsistsofoneormoredatatablesand,optionally,therelationshipsthatlinkthetablestogether.ExecutingaCommandandAccessingOutputParameters.ThisscenarioillustrateshowyoucanusetheExecuteNonQuerymethodtoretrieveasinglerowthatcontainsmultiplecolumnvalues.ExecutingaCommandandAccessingaSingleItemResult.ThisscenarioillustrateshowyoucanusetheExecuteScalarmethodtoperformasingle-itemlookup.PerformingMultipleUpdatesWithinaTransaction.ThisscenarioillustrateshowyoucanusetheExecuteNonQuerymethodfromwithinatransactiontoperformmultipleoperationsagainstadatabase,whereitisessentialthateitheralloperationssucceedornonesucceed.UsingaDataSettoUpdateaDatabase.Thisscenarioillustrateshow,afterchangingaDataSetobject,youcanusetheUpdateDataSetmethodtoupdatethedatabaseandmakeyourchangespermanent.RetrievingMultipleRowsasXML.ThisscenarioillustrateshowyoucanusetheExecuteXmlReadermethodtoretrievedatafromaSQLServerandhavethatdatareturnedinXMLformat.RetrievingDataasObjects.Thisscenariodemonstrateshowyoucanuse
![Page 527: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/527.jpg)
thedataaccessorsincludedintheblocktoretrievedataasasequenceofobjectsofaspecifiedtypefromthedatastore.PerformingAsynchronousDataAccess.ThisscenariodemonstrateshowyoucanusetheasynchronousversionoftheExecuteReadermethodtoreaddatafromadatastoreasynchronously,andthenaccesstheresultsusingacallbackthatindicateswhenthemethodcompletes.
ThistopichelpsyouimplementyourapproachbyusingtheDataAccessApplicationBlock.Itdoesnothelpyouchoosethecorrectapproachforyourparticularsituation(forexample,itdoesnothelpyouchoosebetweenaDataSetandaDbDataReader).Forguidanceonapproachestodataaccess,seethefollowingMicrosoftpatterns&practicesguides:
.NETDataAccessArchitectureGuideINFO:MicrosoftGuideforDesigningDataTierComponentsandPassingDataThroughTiersImproving.NETApplicationPerformanceandScalability
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 528: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/528.jpg)
MicrosoftEnterpriseLibrary5.0
UsingaDbDataReadertoRetrieveMultipleRows
Acommondatabasetaskistoretrieveanddisplayinformation.Forexample,anonlineretailapplicationmayneedtodisplayalistofproductswithinaspecifiedcategory.
![Page 529: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/529.jpg)
TypicalGoals
![Page 530: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/530.jpg)
Solution
![Page 531: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/531.jpg)
UsingExecuteDataReader
![Page 532: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/532.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 533: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/533.jpg)
MicrosoftEnterpriseLibrary5.0
UsingaDataSettoRetrieveMultipleRows
Inamulti-tiersystem,youmayneedtopassdatafromadataaccesscomponenttoamiddle-tierbusinesscomponent.Thedataisretrievedfromthedatabaseandsentback,throughthedataaccesslayer,tothebusinesslayer.TheinformationiscontainedintheDataSetobject.
![Page 534: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/534.jpg)
TypicalGoals
![Page 535: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/535.jpg)
Solution
![Page 536: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/536.jpg)
UsingExecuteDataSet
![Page 537: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/537.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 538: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/538.jpg)
MicrosoftEnterpriseLibrary5.0
ExecutingaCommandandAccessingOutputParameters
Acommondatabasetaskistoretrievespecific,multiple-columnvalues.Forexample,inaWeb-basedonlineretailapplication,youmaywanttoretrievefullproductdetailsforacertainproductinresponsetoauserrequest.
![Page 539: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/539.jpg)
TypicalGoals
![Page 540: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/540.jpg)
Solution
![Page 541: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/541.jpg)
UsingExecuteNonQuery
![Page 542: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/542.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 543: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/543.jpg)
MicrosoftEnterpriseLibrary5.0
ExecutingaCommandandAccessingaSingleItemResult
Therearemanysituationsinwhichyouhavetoperformasingle-itemlookup.Forexample,anonlineretailermaywanttouseaproductIDtoretrieveaproductnameoruseacustomerIDtoretrieveacreditrating.
![Page 544: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/544.jpg)
TypicalGoals
![Page 545: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/545.jpg)
Solution
![Page 546: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/546.jpg)
UsingExecuteScalar
![Page 547: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/547.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 548: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/548.jpg)
MicrosoftEnterpriseLibrary5.0
PerformingMultipleUpdatesWithinaTransaction
Whenanapplicationexecutesmultipleoperationsagainstadatabase,acommonrequirementisthatalloftheoperationsmustsucceedorthedatabasemustrollbacktoitsoriginalstate(thatis,itsstatebeforetheoperationsbegan).Thisall-or-nothingrequirementisreferredtoasatransaction.Transactionsensuretheintegrityofadatabasesystem'sstate.Forexample,inaclassicbankingscenario,anapplicationmustdebitoneaccountandcreditanotherwithaparticularamountofmoney.Forproperaccounting,itisessentialthateitherbothoperationssucceedorneitheroperationsucceeds.Thismeansthatbothoperationsshouldbeperformedinthecontextofasingletransaction.
![Page 549: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/549.jpg)
TypicalGoals
![Page 550: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/550.jpg)
Solution
![Page 551: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/551.jpg)
UsingExecuteNonQueryinaTransactionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 552: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/552.jpg)
MicrosoftEnterpriseLibrary5.0
UsingaDataSettoUpdateaDatabase
Databasesmustbeperiodicallyupdatedwithnewinformation.Forexample,inaWeb-basedonlineretailapplication,youmaywanttoaddanewcustomertothedatabase,modifythenameassociatedwithacustomerID,ordeleteacustomerrecordentirely.
![Page 553: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/553.jpg)
TypicalGoals
![Page 554: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/554.jpg)
Solution
![Page 555: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/555.jpg)
UsingUpdateDataSet
![Page 556: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/556.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 557: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/557.jpg)
MicrosoftEnterpriseLibrary5.0
RetrievingMultipleRowsasXML
AnexampleofwhereyoumaywanttouseXMLdataiswithinane-commerceapplicationthatallowsclientstorequestaproductcatalogthatisinXMLformat.
![Page 558: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/558.jpg)
TypicalGoals
![Page 559: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/559.jpg)
Solution
![Page 560: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/560.jpg)
UsingExecuteXmlReader
![Page 561: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/561.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 562: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/562.jpg)
MicrosoftEnterpriseLibrary5.0
RetrievingDataasObjects
Thisscenariodemonstratesoneofthewaysthatyoucanusethedataaccessorsprovidedwiththeblocktoreaddatafromadatastoreandreturnitasasequenceofobjectsofthetypeyouspecify.TheDataAccessApplicationBlockprovidestwotypesofaccessors,forstoredproceduresorforusewithSQLstatements,inadditiontoarangeofclassesthathelpyoutomapparameterstothequeryandmapthereturneddatatothetypeofobjectyourequire.Forinformationabouttheseclasses,seeReturningDataasObjectsforClientSideQuerying.
![Page 563: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/563.jpg)
TypicalGoals
![Page 564: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/564.jpg)
Solution
![Page 565: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/565.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 566: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/566.jpg)
MicrosoftEnterpriseLibrary5.0
PerformingAsynchronousDataAccess
ThisscenariodemonstrateshowyoucanusetheasynchronousversionoftheExecuteReadermethodtoreaddatafromadatastoreasynchronously,andthenaccesstheresultsusingacallbackthatindicateswhenthemethodcompletes.YoudothisusingtheBeginExecutereaderandEndExecuteReadermethodsoftheDatabaseclass.
Note:AsynchronousdataaccessisnotsupportedbyallADO.NETdataproviders.TheDatabaseclassexposesaBooleanpropertynamedSupportsAsyncthatyoucantesttocheckatruntimeifasynchronousoperationsaresupported.Ifthispropertyreturnsfalse,anyasynchronousmethodsyoucallwillthrowanInvalidOperationException.InEnterpriseLibrary5.0,theonlydatabasetypethatsupportsasynchronousoperationistheSqlDatabaseclass.
![Page 567: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/567.jpg)
TypicalGoals
![Page 569: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/569.jpg)
UsingBeginExecuteReaderandEndExecuteReaderwithaCallback
![Page 570: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/570.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 571: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/571.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheDataAccessApplicationBlock
TheDataAccessApplicationBlockincludesthefollowingfeatures:Asimpleandefficientwayofworkingwithdifferentdatabasesystems(seeDesigningforSimplifiedDataAccess)Awayofdevelopingdatabase-agnosticapplications(seeDesigningforDatabase-AgnosticApplications)Aneasywaytoadjustandvalidatethedatabaseconfigurationsettings
![Page 572: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/572.jpg)
DesignGoals
![Page 573: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/573.jpg)
DesignHighlightsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 574: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/574.jpg)
MicrosoftEnterpriseLibrary5.0
DesigningforSimplifiedDataAccess
Developersfacemanyimplementationchoicesandrequirementswhentheybuilddataaccesssolutions.Theymustaccessthedatainavarietyofways,andtheirsolutionsmustworkwithdifferenttypesofdatabases,eachofwhichhandlesdataaccessdifferently.Asaresult,developersmayfindthemselvesduplicatingcodethatperformscommontasks,suchasmanagingconnectionsandassigningparameterstocommands.
Anotherchallengeismaintainingaconsistentapproachinhowdataaccessoperationsareimplemented.Itmaybenecessarytomaintainthisconsistencyacrosssingleprojects,multipleprojects,orenterprise-scalesolutions.Uniformmethodsofdataaccessmakethecodeeasiertounderstand,morepredictable,andeasiertomaintain.
TheDataAccessApplicationBlocksimplifiesdataaccessbyencapsulatingthelogicthatperformscommondatabaseoperations.Thesemethodsalsohandlecommonhousekeepingtaskssuchasopeningandclosingconnections.Theyaredatabase-agnostic,whichmeansthattheyworkwithSQLServerandOracledatabasesanddonotrequiremodificationtodoso.Applicationswrittenforonetypeofdatabaseusethesamemethodsasthosewrittenforanothertypeofdatabase.Thismeansthatapplicationsareconsistentinthewaysthattheyaccessdata.Inaddition,theGenericDatabaseclasssupportsmanyofthesesamefeaturesacrossADO.NETdataproviders.
![Page 575: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/575.jpg)
DesignImplications
![Page 576: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/576.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 577: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/577.jpg)
MicrosoftEnterpriseLibrary5.0
DesigningforDatabase-AgnosticApplications
TheDataAccessApplicationBlockprovidesanextensibleframeworkforsupportingmultipletypesofrelationaldatabases.Applicationsthatusetheapplicationblockareportableacrossdifferentdatabasesystems.
Thereareanumberofgeneraldataaccesstools—suchasOpenDatabaseConnectivity(ODBC)orOLEDB—thatcanprovideaccesstoavarietyofdatasources.Onedrawbacktothesetoolsisthathowtheyareuseddependsonthetargetdatabase.Thatmeansthatprogrammersneedtounderstandvariousprogrammingmodelstoaccessdifferentdatabasetypes.Movinganapplicationtoadifferentdatabasecouldrequireasignificantamountofrecoding.
AnotherdrawbacktotheODBCorOLEDBapproachisthatperformancemaysuffer.Genericdataprovidersareslowerthanthoseoptimizedforaparticulardatasource.TheDataAccessApplicationBlockprovidesanimplementationthatfeaturesbothportabilityandoptimizedperformance.
![Page 578: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/578.jpg)
CopyCode
CopyCode
AbstractionoftheDatabaseSystemTheDataAccessApplicationBlockbuildsonthecapabilitiesprovidedbyADO.NETtocreateadatabase-agnosticprovidermodel.Thefollowingaresomeofthefeaturesitprovides:
Itstandardizesparameternames.Forexample,itsuppliesthe"@"characterforSQLparameternames.ItconfiguresthestoredprocedurepackagenamemappingforOracledatabases.ItusesADO.NETstaticmethodsforSQLServerandOracletosupportagnosticparameterdiscovery.ItaddsthecursorparameterforresultsreturnedbyanOraclestoredprocedure.
ThemajorityofthedataaccessmethodsareavailablethroughtheabstractDatabaseclass.ClientcodecanrefertothesemethodsintheircoderegardlessoftheactualDatabase-derivedobjectused.Forexample,thefollowingcodeshowshowtousetheExecuteDataSetmethod.C#
Databasedb;
...
db.ExecuteDataSet(cmd);
VisualBasic
DimdbAsDatabase
...
db.ExecuteDataSet(cmd)
TheblockcreatesthespecificDatabase-derivedobject.ItreturnsanobjectoftypeDatabase,thusallowingtheclientcodetoremaingenericregardingtheactualdatabasetypereturned.
ThemethodsavailableontheDatabaseclassrequireinformationaboutthecommandtobeexecutedaswellasanyassociatedparameters.Different
![Page 579: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/579.jpg)
databasesystemshandlecommandsandparametersindifferentways.Database-derivedclassesprovidemethodsthatacceptparameterinformation;thespecificdatabasesystemsprovidetheirownderivedimplementationstohandleparameterparameters.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 580: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/580.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingtheDataAccessApplicationBlock
Initsoriginalstate,theDataAccessApplicationBlockworkswellfortypicaldataaccessscenarios.However,theremaybetimeswhenyouneedtocustomizesomeoftheapplicationblock'sbehaviortobettersuityourapplication'srequirements.YoucanextendtheDataAccessApplicationBlockusingthebuilt-inextensionpoints.Youcanalsomodifytheapplicationblockbymakingchangestoitssourcecode.Formoredetails,seethefollowingtopics:
ExtendingtheDataAccessApplicationBlockExtendingandModifyingEnterpriseLibrary
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 581: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/581.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingtheDataAccessApplicationBlock
Youextendtheapplicationblockthroughdesignatedextensionpoints.Typically,thesearecustomclassesthatyoumustwrite.Thecustomclassesimplementaparticularinterfaceorderivefromanabstractclass.Becausethesecustomclassesexistinyourapplicationspace,youdonothavetomodifyorrebuildtheapplicationblock.Instead,youuseconfigurationsettingstodesignateyourextensions.
Currently,youcanextendtheapplicationblockbyaddinganewdatabasetype.Youwoulddothisifyourapplicationneedsdatabase-specificfeaturesfromadatabaseotherthantheSQLServerdatabaseortheOracledatabase.Youonlyneedtoextendtheapplicationblockiftheapplicationblock'sGenericDatabaseclassandtheADO.NETdataproviderforthedatabasesystemdonotprovidethefeaturesyourequire.Forexample,theGenericDatabaseobjectdoesnotsupportspecialparameterprefixesforstoredproceduresorinvokemethodsthatarenotontheDbCommandclassortheDbConnectionclass.Inaddition,theGenericDatabaseclassdoesnotsupportparameterdiscovery.
YoucouldextendtheapplicationblockbycreatinganewdatabaseclassthatsupportsfeaturesnotexposedbytheADO.NETdataprovider.Forexample,yourdatabaseclasscouldsupportparameterdiscovery.Youcouldalsoextendtheapplicationblocktoallowyourclientcodetoremaindatabase-agnosticthroughtypeconversionsorbymanagingSQLsyntaxconversions.BuildingacustomdatabaseclassallowsyourapplicationtosupporttheentireDataAccessApplicationBlockAPIsetandtobemorecompatiblewiththesyntaxesofotherdatabases.Tolearnmore,seeAddingaNewApplicationBlockDatabaseProvider.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 582: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/582.jpg)
MicrosoftEnterpriseLibrary5.0
AddingaNewApplicationBlockDatabaseProvider
Iftherelationaldatabasesystemyouareusingdoesnotalreadyhaveanapplicationblockdatabaseprovider,youcancreateyourown.Thisisonlynecessaryiftheapplicationblock'sGenericDatabaseclassdoesnotmeettherequirementsofyourapplication.(ThisassumesthatthereisanADO.NETDbProviderFactorytypeforthedatabasesystemyouareusing.)Tocreateanewdatabaseprovider,youmustcreateanewdatabaseclassthatderivesfromtheDatabaseclass.Additionally,ifyouwantyourclientcodetoremaindatabase-agnostic,youmighthavetowriteadditionalcodetoperformsuchtasksastypeconversion.
![Page 583: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/583.jpg)
CreatingaNewDatabaseClass
![Page 584: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/584.jpg)
ConfiguringYourApplicationtoUsetheNewProvider
![Page 585: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/585.jpg)
RecommendationsforCreatingaDatabaseProviderToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 586: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/586.jpg)
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetoseethattheinitialdeploymentoftheDataAccessApplicationBlockisplannedandmanagedandthatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheapplicationblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheapplicationblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheapplicationblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheDataAccessApplicationBlock,seethefollowingtopics:
DataAccessApplicationBlockPerformanceCountersDataAccessApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 587: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/587.jpg)
MicrosoftEnterpriseLibrary5.0
DataAccessApplicationBlockPerformanceCounters
ThefollowingtabledescribestheDataAccessApplicationBlockperformancecounters.
PerformanceCounterName
Description
CommandsExecuted/sec
Therateatwhichdatabasecommandswereexecuted.
CommandsFailed/sec Therateatwhichdatabasecommandsfailedtoexecute.
ConnectionsFailed/sec Therateatwhichdatabaseconnectionsfailedtoopen.
ConnectionsOpened/sec
Therateatwhichdatabaseconnectionswereopened.
TotalCommandsExecuted
Thetotalnumberofdatabasecommandsthatwereexecuted.
TotalCommandsFailed Thetotalnumberofdatabasecommandsthatfailedtoexecute.
TotalConnectionsFailed
Thetotalnumberofdatabaseconnectionsthatfailedtoopen.
TotalConnectionsOpened
Thetotalnumberofdatabaseconnectionsthatwereopened.
Aratecountersamplesanincreasingcountofeventsovertimeanddividesthevaluesbythechangeintimetodisplayarateofactivity.Formoreinformationaboutperformancecounters,seeOverviewofPerformanceMonitoringonTechNet.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,pleasesendemailto
![Page 588: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/588.jpg)
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 589: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/589.jpg)
MicrosoftEnterpriseLibrary5.0
DataAccessApplicationBlockEventLogEntries
TheDataAccessApplicationBlockisinstrumentedtologentriestotheapplicationeventlogforavarietyofevents.ThistopicliststheDataAccessApplicationBlockeventlogentries.
![Page 590: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/590.jpg)
ConnectionFailedEvent
![Page 591: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/591.jpg)
CommandExecutedEvent
![Page 592: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/592.jpg)
CommandFailedEvent
![Page 593: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/593.jpg)
DataConfigurationFailureEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 594: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/594.jpg)
MicrosoftEnterpriseLibrary5.0
TheExceptionHandlingApplicationBlock
TheEnterpriseLibraryExceptionHandlingApplicationBlockhelpsdevelopersandpolicymakersimplementcommondesignpatternsandcreateaconsistentstrategyforprocessingexceptionsthatoccurinallarchitecturallayersofanenterpriseapplication.Itisdesignedtosupportthetypicalcodecontainedincatchstatementsinapplicationcomponents.Insteadofrepeatingthiscode(suchascodethatlogsexceptioninformation)inidenticalcatchblocksthroughoutanapplication,theExceptionHandlingApplicationBlockallowsdeveloperstoencapsulatethislogicasreusableexceptionhandlers.TheExceptionHandlingApplicationBlockincludesfourexceptionhandlers:
Wraphandler.Thisexceptionhandlerwrapsoneexceptionaroundanother.Replacehandler.Thisexceptionhandlerreplacesoneexceptionwithanother.Logginghandler.Thisexceptionhandlerformatsexceptioninformation,suchasthemessageandthestacktrace.ThenthelogginghandlerpassesthisinformationtotheEnterpriseLibraryLoggingApplicationBlocksothatitcanbepublished.FaultContractexceptionhandler.ThisexceptionhandlerisdesignedforuseatWindows®CommunicationFoundation(WCF)serviceboundaries,andgeneratesanewFaultContractfromtheexception.
YoucanextendtheExceptionHandlingApplicationBlockbyimplementingcustomhandlers,andadministratorscanmanagetheconfigurationoftheblockto,forexample,turnonadditionaldebugginginstrumentationorchangethebehavioroftheblockinlinewithchangestobusinessrequirements.TheconfigurationcanevenbemanagedusingGroupPolicytools.
ThissectionincludesthefollowingtopicsthatwillhelpyoutounderstandandusetheExceptionHandlingApplicationBlock:
WhatDoestheExceptionHandlingApplicationBlockDo?Thistopicprovidesabriefoverviewthatwillhelpyoutounderstandwhattheblockcando,andexplainssomeoftheconceptsandfeaturesitincorporates.Italsoprovidesasimpleexampleofthewaythatyoucanwritecodetousetheblock.
![Page 595: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/595.jpg)
WhenShouldIUsetheExceptionHandlingApplicationBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andanyalternativetechniquesyoumayconsider.Italsoprovidesdetailsofanylimitationsoftheblockthatmayaffectyourdecisiontouseit.DevelopingApplicationsUsingtheExceptionHandlingApplicationBlock.ThistopicexplainshowtoconfiguretheExceptionHandlingApplicationBlock,howtoaddtheblocktoyourapplications,howtodetermineappropriateexceptionhandlingpolicies,howtospecifydifferenthandlingactions,andhowtosendanexceptiontotheExceptionHandlingBlock.KeyScenarios.ThistopicshowsdifferentwaystousetheExceptionHandlingApplicationBlockinyourownapplications.DesignoftheExceptionHandlingApplicationBlock.Thistopicexplainsthedecisionsthatwentintodesigningtheblockandtherationalebehindthosedecisions.ExtendingandModifyingtheExceptionHandlingApplicationBlock.Thistopicexplainshowtoextendtheapplicationblockbyaddingcustomhandlersandformatters.Italsogivessomeadviceabouthowtomodifythesourcecode.DeploymentandOperations.Thistopicexplainshowtodeployandupdatetheblockassemblies.
![Page 596: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/596.jpg)
MoreInformationFormoreinformation,seethefollowingMicrosoft®patterns&practicesguides:
ApplicationArchitecturefor.NET:DesigningApplicationsandServicesDesignGuidelinesforExceptions
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 597: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/597.jpg)
MicrosoftEnterpriseLibrary5.0
WhatDoestheExceptionHandlingApplicationBlockDo?
Arobustandwell-plannedexceptionhandlingstrategyisavitalfeatureofyourapplicationdesignandimplementationthatwillhelpyouavoidriskssuchasexposingerrormessagescontainingsensitiveinformation,orleavingyourapplicationandsystemsinaninconsistentstateandopentoattackwhenanerroroccurs.
Anexceptionhandlingstrategyconsistsofaseriesofpoliciesthatdefinehowyouwillpresentclearandappropriatemessagestousersandhowyoucanprovideassistanceforoperators,administrators,andsupportstaff.Acomprehensiveexception-handlingstrategywillusually:
NotifytheuserwithafriendlymessageStoredetailsoftheexceptioninaproductionlogorotherrepositoryAlertthecustomerserviceteamtotheerrorAssistsupportstaffincross-referencingtheexceptionandtracingthecause
TheExceptionHandlingApplicationBlockcanhelpyoutodefineandcreateconsistentexceptionmanagementstrategiesbyimplementingthreewell-knowndesignpatterns:
ExceptionShielding.Thispatternensuresthatyourapplicationdoesnotleaksensitiveinformation,nomatterwhatrun-timeorsystemeventmayoccurtointerruptnormaloperation.Andonamoregranularlevel,itcanpreventyourassetsfrombeingrevealedacrosslayer,tier,process,orserviceboundaries.ExceptionLogging.Thispatterncanhelpyoutodiagnoseandtroubleshooterrors,audituseractions,andtrackmaliciousactivityandsecurityissuesbyloggingdetailsofexceptionsanderrorsthatoccur.ExceptionTranslation.Thispatterndescribeshowyoucanwrapexceptionswithinotherexceptionsspecifictoalayertoensurethattheyactuallyreflectuserorcodeactionswithinthelayeratthattime,andnotsomemiscellaneousdetailsthatmaynotbeuseful.
TheExceptionHandlingApplicationBlockletsyouassociateexceptiontypeswithnamedpolicies.Youdothisbyusingtheconfigurationtools.Policiesspecifytheexceptionhandlersthatexecutewhentheblockprocessesa
![Page 598: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/598.jpg)
particularexceptiontype.Exceptionhandlersare.NETclassesthatencapsulateexceptionhandlinglogicandimplementtheExceptionHandlingApplicationBlockinterfacenamedIExceptionHandler.
Youcanchainthesehandlerstogethersothataseriesofthemexecutewhentheassociatedexceptiontypeishandled.Thefollowingaresomeexamplesofnamedpoliciesanddescriptionsofwhattheymightprovide:
Basepolicy.Thispolicylogstheexceptionandre-throwstheoriginalexception.Securepolicy.Thispolicylogstheexception,replacestheoriginalexceptionwithacustomexception,andthrowsthenewexception.Expressivepolicy.Thispolicywrapstheoriginalexceptioninsideanotherexceptionandthrowsthenewexception.
Thefollowingschematicillustratesexamplesofcross-layerandsingle-applicationcomponentexceptionhandling.
Figure1Examplesofexceptionhandlingpolicies
![Page 599: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/599.jpg)
Inthisexample,exceptionsthatoccurinthedataaccesslayerareloggedandthenwrappedinsideanotherexceptionthatprovidesmoremeaningfulinformationtothecallinglayer.Withinthebusinesscomponentlayer,theexceptionsareloggedbeforetheyarepropagated.Anyexceptionsthatoccurinthebusinesscomponentlayerandthatcontainsensitiveinformationarereplacedwithexceptionsthatnolongercontainthisinformation.Thesearesenttotheuserinterface(UI)layeranddisplayedtotheuser.
Forinformationabouthowtodevelopexceptionmanagementstrategies,seeDeterminingAppropriateExceptionPoliciesandActions.
![Page 600: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/600.jpg)
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 601: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/601.jpg)
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheExceptionHandlingApplicationBlock?
TheExceptionHandlingApplicationBlockisbestusedinsituationsthatrequireuniformandflexibleproceduresforhandlingexceptions.Forexample,youmightwantconsistentexceptionhandlingproceduresforallcomponentsinaparticulartierofanapplication'sarchitecture.Inaddition,becauseofchangingsecurityorotheroperationalissues,youmightwanttheabilitytochangepoliciesasneeded,withoutrequiringchangestotheapplicationsourcecode.TheExceptionHandlingApplicationBlock,inconjunctionwiththeEnterpriseLibraryconfigurationtools,letsyouaccomplishbothtasks.
Forexample,youcouldusetheconfigurationtoolstodefineapolicythatuseshandlerstoreplaceexceptionsthatcontainsensitiveinformationwithversionsthatdonotincludethatinformation.Theblockthenimplementsthispolicyacrossthecomponentsthatcontaincodethatspecifiesthispolicyshouldbeused.
TheExceptionHandlingApplicationBlockisnotlimitedtocross-tierapplications.Itcanalsobeusedwithinaparticularapplication.Forexample,youcandefinepoliciesthatlogexceptioninformationordisplayexceptioninformationtotheuser.
Ineithercase,policiesareconfiguredwithoutchangingtheapplication'scode.Thismakesthemeasytomaintainorchangewhennewsituationsoccur.Notethat,inallcases,youshouldusetheblocktoperformonlythosetasksthatarespecifictoexceptionhandlingandthatdonotintersectwiththeapplication'sbusinesslogic.Forexample,youcanremovethehandlersthatloganexceptionorwraponeexceptioninanotherwithoutaffectingsuchbasiccapabilitiesasupdatingacustomerdatabase.
![Page 602: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/602.jpg)
ScenariosfortheExceptionHandlingBlock
![Page 603: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/603.jpg)
BenefitsoftheExceptionHandlingApplicationBlock
![Page 604: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/604.jpg)
LimitationsoftheExceptionHandlingApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 605: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/605.jpg)
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheExceptionHandlingApplicationBlock
ThistopicdescribeshowtodevelopapplicationsbyusingtheExceptionHandlingApplicationBlock.Itfirstexplainshowtoconfiguretheblockandreferenceitinyourapplications.Next,itdescribeshowtodevelopexception-handlingstrategiesforyourapplications,andexplainshowtousetheblockinspecificscenariossuchasloggingandpropagatingexceptions.Thissectionincludesthefollowingtopics:
EnteringConfigurationInformationAddingApplicationCodeDeterminingAppropriateExceptionPoliciesandActionsSpecifyingDifferentHandlingActionsBasedonExceptionTypeandPolicySendinganExceptiontotheExceptionHandlingApplicationBlockHandlingandThrowingExceptions
Allapplicationblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompileit.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 606: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/606.jpg)
MicrosoftEnterpriseLibrary5.0
EnteringConfigurationInformation
TheseproceduresexplainhowtoconfiguretheExceptionHandlingApplicationBlock.Forinformationaboutusingtheconfigurationtools,seeUsingtheConfigurationTools.FordetailsoftheschemafortheExceptionHandlingApplicationBlockconfiguration,seeSourceSchemafortheExceptionHandlingApplicationBlock.Youcanalsoconfiguretheblockincodebyusinganalternateconfigurationsource.Formoreinformation,seeAdvancedConfigurationScenariosandUsingtheFluentConfigurationAPI.
ToaddtheExceptionHandlingApplicationBlock1. Openyourconfigurationfileintheconfigurationeditor.Formore
information,seeConfiguringEnterpriseLibrary.2. OpentheBlocksmenuandthenclickAddExceptionHandling
Settings.3. ThiscreatesanExceptionHandlingSettingssectionwithone
exceptionhandlingpolicythatbydefaultiscalledPolicy,andasingleitemnamedAllExceptionsintheExceptionTypescolumnthatdefinesallexceptionsoftypeSystem.ExceptionorthatinherittheSystem.Exceptionclass.
4. ToeditthepropertiesoftheExceptionHandlingSettingssection,clickthechevronarrowtherightoftheExceptionHandlingSettingsheading.
5. (Optional)Ifyouwanttoencrypttheconfiguration,makeaselectionfromtheProtectionProviderdrop-downlist.YoucanselecttheRsaProtectedConfigurationProviderortheDataProtectedConfigurationProvider.SeeEncryptingConfigurationDataforinformationabouttherestrictionsonusingtheRsaProtectedConfigurationProvider.
6. (Optional)Ifyouwanttorunyourapplicationinpartialtrustmode,changetheRequirePermissionpropertytoFalse.ThedefaultisTrue.
Toconfigureanexceptionhandlingpolicy1. Toaddanexceptionhandlingpolicy,clicktheplussigniconinthe
PoliciescolumnandclickAddPolicy.Thisaddsanewexceptionhandlingpolicyitem.Clicktheexpanderarrowontheleftofthepolicy
![Page 607: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/607.jpg)
headingifthepropertiesarenotvisible.2. (Optional)Renamethepolicy.IntheNametextbox,typetherequired
policyname.3. Toaddanexceptiontypetoapolicy,right-clickthepolicyitemand
clickAddExceptionTypetodisplaythetypeselectordialog.4. Selecttheexceptiontypeinthetypeselectordialogbox.Tofilterthe
list,typethefilterstringintheFiltereditbox.Forexample,type"string"tofilterforallclassescontainingthewordstring.Ifthetypeyouwantisnotlisted,clickAddfromFileorAddfromGAC(fromtheglobalassemblycache)andfindtheassemblycontainingthetypeyouwant,andthenclickOK.ThiscreatesthenewpolicyandadefaultAllExceptionsitem.
5. ClicktheexpanderarrowtotheleftonthenewAllExceptionsnodeintheExceptionTypescolumntodisplaythepropertiesiftheyarenotvisible.
6. SelectthePosthandlingactionyouwant.Thepost-handlingactiondetermineswhatactionwilloccuraftertheexceptionhandlingchaincompletes.Bydefault,thepost-handlingactionissettoNotifyRethrow.Ingeneral,whenyouusetheProcessmethod,youwillconfiguretheexceptionhandlingpolicywithapost-handlingactionofThrowNewExceptionunlessyouwantyourcodetocontinuetoexecuteaftertheblockhandlestheexception.Validvaluesarethefollowing:
NotifyRethrow.Theblockexecutesallhandlersforthisexceptionandreturnstruetotheapplicationatthepointatwhichthepolicywasinvoked.Applicationscheckingthisvaluere-throwtheoriginalexception.However,ifyouusetheProcessmethodyoucannotdetectthevaluereturnedbytheExceptionHandlingApplicationBlock.Internally,theProcessmethodcallstheHandleExceptionmethod,andthrowstheexceptionifthismethodreturnstrue.Therefore,typicallyyourcodewilljustthrowanyexceptionthatisraised.ThrowNewException.Theblockexecutesallhandlersforthisexceptionandthrowstheexceptionthatexistsafterthefinalhandlerruns.However,ifyouusetheoverloadoftheHandleExceptionmethodthattakesanoutparameterthatreturnsthefinalexceptionfromthehandlers,itdoesnot
![Page 608: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/608.jpg)
automaticallythrowtheexception;youmustdothisinyourcode.None.Theblockexecutesallhandlersforthisexceptionandreturnsfalsetotheapplicationatthepointatwhichthepolicymethodwasinvoked.Applicationscheckingthisvalueresumeexecution.
7. Toaddadditionalexceptiontypestothepolicy,repeatsteps3to6.8. Toaddanexceptionhandler,rightclicktheAllExceptionsitemoran
exceptionitemyouadded,pointtoAddHandlers,andthenclicktheexceptionhandlertypethatyouwant:
Replaceexceptionhandler.Thisexceptionhandlerreplacesoneexceptionwithanother.Wrapexceptionhandler.Thisexceptionhandlerwrapstheexceptionthatoccurredwithanotherexception.Loggingexceptionhandler.ThisexceptionhandlerformatsexceptioninformationandusestheLoggingApplicationBlocktologexceptioninformation.TheLoggingApplicationBlockisautomaticallyaddedtotheapplicationconfigurationwhenyouselectalogginghandler.Formoreinformation,seeTheLoggingApplicationBlock.FaultContractexceptionhandler.ThisexceptionhandlerisdesignedforuseatWindowsCommunicationFoundation(WCF)serviceboundaries,andgeneratesanewFaultContractfromtheexception.Customexceptionhandler.Thisoptionallowsyoutoconfigurecustomexceptionhandlers.AcustomhandlerisatypethatimplementstheIExceptionHandlerinterfaceandhasaConfigurationElementTypeofCustomHandlerData.ClickAddfromFileinthetypeselectortoaddacustomhandlerthatislocatedinaseparateassembly.
9. Toaddadditionalexceptionhandlerstothepolicy,repeatstep8.10. Ifrequired,changetheorderoftheexceptionhandlersbyright-clicking
thehandleritemheadingandclickingeitherMoveUporMoveDown.Handlersareexecutedintheorderyouspecify.Typically,youwillplaceaLogginghandlerfirstinthelist,followedbyaWraphandleroraReplaceHandler.
11. Seethefollowingsectionofthistopicfordetailsofhowtoconfigure
![Page 609: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/609.jpg)
exceptionhandlers.
![Page 610: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/610.jpg)
ConfiguringExceptionHandlersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 611: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/611.jpg)
MicrosoftEnterpriseLibrary5.0
SourceSchemafortheExceptionHandlingApplicationBlock
ThistopicliststheXMLelementsandattributesusedtoconfiguretheExceptionHandlingApplicationBlock.YoucanmanuallyedittheXMLdata,buttheEnterpriseLibraryConfigurationConsolegreatlysimplifiesthistask.IfyouchoosetomanuallyedittheXML,usetheschemainformationcontainedinthistopic.
Theconfigurationfilehasthefollowingsection-handlerdeclaration.XML
<configSections>
<sectionname="exceptionHandling"
type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings,
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"/>
</configSections>
Thesection-handlerdeclarationcontainsthenameoftheconfigurationsettingssectionandthenameofthesection-handlerclassthatprocessesconfigurationdatainthatsection.ThenameoftheconfigurationsettingssectionisexceptionHandling.Thenameofthesection-handlerclassisExceptionHandlingSettings.ThisclassisintheMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling.Configurationnamespace.
![Page 612: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/612.jpg)
exceptionHandlingElement
![Page 613: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/613.jpg)
exceptionPoliciesChildElement
![Page 614: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/614.jpg)
exceptionTypesChildElement
![Page 615: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/615.jpg)
exceptionHandlersChildElement
![Page 616: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/616.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 617: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/617.jpg)
MicrosoftEnterpriseLibrary5.0
AddingApplicationCode
TheExceptionHandlingApplicationBlockisdesignedtosupportthemostcommonscenariosforhandlingexceptions.Whenyouaddyourapplicationcode,refertothescenariosinKeyScenariosandselecttheonesthatbestsuityoursituation.Usethecodethataccompaniesthescenarioeitherasitisshownhereoradaptitasrequired.
ToprepareyourapplicationtousetheExceptionHandlingApplicationBlock
1. AddareferencetotheExceptionHandlingApplicationBlockassembly.InVisualStudio®,right-clickyourprojectnodeinSolutionExplorer,andthenclickAddReference.ClicktheBrowsetab,selecttheMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling.dllassembly,andthenclickOK.
2. Followingthesameprocedure,setareferencetothefollowingassemblies,
Microsoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.Unity.dllMicrosoft.Practices.Unity.Interception.dll
3. IfyouconfigureyourapplicationtousetheLoggingExceptionHandler,setareferencetoMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dllandtherequiredLoggingApplicationBlockassemblies.ForinformationabouttheLoggingApplicationBlockassemblies,seeAddingApplicationCodeinthedocumentationforTheLoggingApplicationBlock.
4. (Optional)TouseelementsfromtheExceptionHandlingApplicationBlockwithoutfullyqualifyingtheelementreference,youcanaddthefollowingusingstatement(C#)orImportsstatement(VisualBasic®)tothetopofyoursourcecodefile.C#
usingMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling;
![Page 618: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/618.jpg)
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling
Note:ForVisualBasicprojects,youcanalsousetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer,andthenclickPropertiesontheProjectmenu.WhentheProjectDesignerappears,clicktheReferencestab.
Next,addtheapplicationcode.Generally,codethatusestheExceptionHandlingApplicationBlockmustcompletethefollowingsteps:
ObtainaninstanceoftheExceptionManagerclass.Formoredetails,seeCreatingApplicationBlockObjects.Catchanexception.Processanexceptionpolicy.Re-throwtheoriginalexceptionwhereappropriate.
Thefollowingtopicsexplainhowtoincorporatethesestepsintoanapplication:DeterminingAppropriateExceptionPoliciesandActionsSpecifyingDifferentHandlingActionsBasedonExceptionTypeandPolicySendinganExceptiontotheExceptionHandlingApplicationBlockHandlingandThrowingExceptions
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 619: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/619.jpg)
MicrosoftEnterpriseLibrary5.0
DeterminingAppropriateExceptionPoliciesandActions
Thisinformationprovidesanoverviewofmanagingexceptionsinyourapplications.Forcompletedesignandimplementationguidelinesforcreatingexceptionmanagementsystemsthatuse.NETtechnologies,seeDesignGuidelinesforExceptionsonMSDN®.
Tobuildsuccessfulandflexibleapplicationsthatcanbemaintainedandsupportedeasily,youmustuseanappropriatestrategyforexceptionmanagement.Youmustdesignyoursystemtomakesurethatitcandothefollowing:
DetectexceptionsLogandreportinformation
Thefollowingtopicsprovideusefuladviceabouthowyoushoulddevelopyourexceptionmanagementstrategies:
GenerateEventsThatCanBeMonitoredExternallytoHelpSystemOperationExceptionHandlingProcessandtheExceptionHandlingApplicationBlockWhentoCatchExceptionsExceptionPropagationHidingExceptionInformationExceptionNotificationPlanningforExceptionHandling
![Page 620: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/620.jpg)
GenerateEventsThatCanBeMonitoredExternallytoHelpSystemOperation
![Page 621: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/621.jpg)
ExceptionHandlingProcessandtheExceptionHandlingApplicationBlock
![Page 622: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/622.jpg)
WhentoCatchExceptions
![Page 623: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/623.jpg)
ExceptionPropagation
![Page 624: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/624.jpg)
HidingExceptionInformation
![Page 625: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/625.jpg)
ExceptionNotification
![Page 626: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/626.jpg)
PlanningforExceptionHandlingToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 627: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/627.jpg)
MicrosoftEnterpriseLibrary5.0
SpecifyingDifferentHandlingActionsBasedonExceptionTypeandPolicy
TheExceptionHandlingApplicationBlockseparatesthedefinitionofhowanexceptionshouldbeprocessed(whichistheexceptionpolicy)fromtheapplicationcodethatusestheblocktohandleexceptions.Youusetheconfigurationtoolstocreateandnamepolicies.
Byusingexceptionpolicies,theapplicationbehaviorthatoccursinresponsetoanexceptioncanbemodifiedwithoutchangingtheapplicationcode.
![Page 628: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/628.jpg)
ConfiguringExceptionPolicies
![Page 629: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/629.jpg)
ConfiguringExceptionTypes
![Page 630: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/630.jpg)
UnderstandingExceptionHandlersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 631: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/631.jpg)
MicrosoftEnterpriseLibrary5.0
SendinganExceptiontotheExceptionHandlingApplicationBlock
InteractionbetweenapplicationcodeandtheExceptionHandlingApplicationBlockoccurswhentheapplicationcodecatchesanexceptionandsendsittotheblocktobehandled.Applicationdevelopersdonothavetoknowhowexceptionswillbehandledbecausetheyhavetospecifyonlythenameoftherelevantexceptionpolicy.
Therearethreemainscenariosinwhichyoumayneedtohandleexceptions.Themostcommonisthefirstofthese,butthistopicexplainshowyoucanusetheblocktoimplementallthreescenarios.Thescenariosare:
HandlingAllExceptionsinaCatchSectionHandlingSpecificExceptionsinaCatchSectionExecutingCodeBeforeorAfterHandlinganException
![Page 632: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/632.jpg)
HandlingAllExceptionsinaCatchSection
![Page 633: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/633.jpg)
HandlingSpecificExceptionsinaCatchSection
![Page 634: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/634.jpg)
ExecutingCodeBeforeorAfterHandlinganExceptionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 635: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/635.jpg)
MicrosoftEnterpriseLibrary5.0
HandlingandThrowingExceptions
Whenanexceptionoccurs,itpassesupthestackandeachcatchblockcanpotentiallyhandleit.Theorderofcatchstatementsisimportant.Putcatchblocksthattargetspecificexceptionsbeforeageneralcatchblock.Otherwise,thecompilermightissueanerror.Thecommonlanguageruntime(CLR)determinesthepropercatchblockbymatchingthetypeoftheexceptiontothenameoftheexceptionspecifiedinthecatchblock.Ifthereisnospecificcatchblock,ageneralcatchblock,ifitexists,handlestheexception.
![Page 636: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/636.jpg)
DebuggingandExceptionPropagation
![Page 637: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/637.jpg)
HandlingSpecificExceptions
![Page 638: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/638.jpg)
User-FilteredExceptionsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 639: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/639.jpg)
MicrosoftEnterpriseLibrary5.0
KeyScenarios
Thistopicdescribesthemostcommonsituationsthatdevelopersmustaddresswhenhandlingexceptions.Eachscenarioexplainsthetask,describesareal-worldsituationwheresuchataskmightoccur,andincludescodethatdemonstrateshowtousetheExceptionHandlingApplicationBlocktocompletethetask.Thescenariosarethefollowing:
LogginganException.Thisscenariodemonstrateshowtousethelogginghandlertocollectexceptioninformation,formatit,andsendittotheLoggingApplicationBlock.ReplacinganException.Thisscenariodemonstrateshowtousethereplacehandlertocreateanewexceptionofadefinedtypethatreplacestheoriginalexception.WrappinganException.Thisscenariodemonstrateshowtousethewraphandlertocreateanewexceptionofadefinedtypethatwrapstheoriginalexceptionwithanotherexceptionthatismorerelevant.PropagatinganException.Thisscenariodemonstrateshowtopropagateanexceptioninitsoriginalstateafterrunningachainofexceptionhandlers.DisplayingUser-FriendlyMessages.Thisscenariodemonstrateshowtoeitherreplaceorwrapanexceptionwithonethatprovidessupportorinstructionalinformationfortheuser.NotifyingtheUser.Thisscenariodemonstratesmethodsforlettingauserknowthatanerrorhasoccurred.AssistingSupportStaff.Thisscenariodemonstrateshowsupportstaffcanmatchauser'serrormessagewiththedetailedinformationthatisstoredintheexceptionlog.
Inaddition,thissectioncontainsthetopicShieldingExceptionsatWCFServiceBoundaries,whichdescribeshowunknownexceptionsoccurringinWindowsCommunicationFoundation(WCF)servicesshouldnotbesenttotheclientapplication,inordertopreventdetailsoftheserviceimplementationfromescapingthesecureboundaryoftheservice.
![Page 640: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/640.jpg)
ExceptionsThatOccurDuringExceptionHandlingToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 641: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/641.jpg)
MicrosoftEnterpriseLibrary5.0
LogginganException
Afrequentlyrequiredexception-handlingtaskistologtheinformationassociatedwiththeexception.TheExceptionHandlingApplicationBlock,inconjunctionwiththeLoggingApplicationBlock,letsyoulogformattedexceptioninformationinlocationsspecifiedintheconfigurationfile.Forexample,clientapplicationstypicallylogapplicationinformationintheeventlog,whileaservercomponentofane-commerceapplicationmaylogexceptionsinadatabase.
![Page 642: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/642.jpg)
TypicalGoals
![Page 643: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/643.jpg)
Solution
![Page 644: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/644.jpg)
UsingtheLoggingHandler
![Page 645: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/645.jpg)
ModifyYourApplication
![Page 646: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/646.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 647: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/647.jpg)
MicrosoftEnterpriseLibrary5.0
ReplacinganException
Afrequentlyrequiredexception-handlingtaskistoreplacetheoriginalexceptionwithanotherexception.Forexample,ifanexceptionisgoingtocrossatrustboundary,youmaynotwanttosendtheoriginalexceptionbecauseitcontainssensitiveinformation.
![Page 648: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/648.jpg)
TypicalGoals
![Page 649: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/649.jpg)
Solution
![Page 650: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/650.jpg)
UsingtheReplaceHandler
![Page 651: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/651.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 652: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/652.jpg)
MicrosoftEnterpriseLibrary5.0
WrappinganException
Afrequentlyrequiredexception-handlingtaskiswrappingoneexceptionwithadifferentexception.WrappinganexceptioncreatesanewexceptionofadefinedtypeandsetstheoriginalexceptionastheInnerExceptionobjectofthenewexception.Usethewrappingcapabilityinsituationswheretheoriginalexceptiontypemustbemappedtoanewexceptiontypeforusebyothertierswithinthearchitectureoftheapplication.Youcanencapsulateandinterpretdetailsoftheunderlyinglayer'soriginalexceptionwithoutlosinganydetailsaboutthatexception.Youcanwraptheoriginalexceptioneitherinanexistingexceptiontypeorinacustomexceptiontypethatyoucreate.Thefollowingexplainsasituationwhenyouwouldwanttowrapanexception:
1. AbusinessservicenamedUpdateCustomercallsadatalayerservice.2. Thedatalayerservicefailsandthrowsanexception.Thiscouldbeany
oneofmanyexceptionsthatindicatethattheupdatefailed.Somesetsoftheseexceptionsindicatethatrecoverymaybepossiblewitharetry(forexample,ifarecordislocked)whileothersarenon-recoverable(forexample,ifthereisaconcurrencyviolationoradirtyrecord).
3. Theexceptionhandlermapsandwrapsthesesetsofexceptionsintotwocustomexceptiontypes,RecoverableUpdateExceptionandFatalUpdateException.
4. Thebusinessservicehandlestheexceptionbasedonthewrappingtypeandtakestheappropriateaction,eventhoughitisinsulatedfromdetailedknowledgeoftheunderlyingfailure.
![Page 653: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/653.jpg)
TypicalGoals
![Page 654: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/654.jpg)
Solution
![Page 655: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/655.jpg)
UsingtheWrapHandler
![Page 656: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/656.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 657: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/657.jpg)
MicrosoftEnterpriseLibrary5.0
PropagatinganException
Afrequentlyrequiredexception-handlingtaskistoallowtheoriginalexceptiontopropagateupthecallstackunchanged.Youmaywanttodothisbecausethehandlersonlyperformactionssuchasloggingthatleavetheexceptionunchangedorbecauseotheractions,suchaswrappingandreplacing,havebeenturnedoff.Forexample,aroutinewithinabusinesslogiccomponentmaylogexceptionsatthepointwheretheyaredetected.Itthenpropagatesthatexceptiontothecallerforadditionalhandling.
![Page 658: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/658.jpg)
TypicalGoals
![Page 659: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/659.jpg)
Solution
![Page 660: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/660.jpg)
PropagatinganException
![Page 661: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/661.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 662: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/662.jpg)
MicrosoftEnterpriseLibrary5.0
DisplayingUser-FriendlyMessages
Youmaywanttoreplacethemessageintheoriginalexceptionwithamoreappropriate,user-friendlymessage.Todothis,youmustreplacetheoriginalexceptionwithanotherexceptionthathasamoreappropriatemessageassociatedwithit.Forexample,exceptionsthatoccurinthedataaccesslayerofanapplicationcanbereplacedwithanexceptionoftypeSystem.ApplicationException.Thisusesthemessage,"Theapplicationisunabletoprocessyourrequestatthistime."Thismessageisthendisplayedtotheuser.
![Page 663: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/663.jpg)
TypicalGoals
![Page 664: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/664.jpg)
Solution
![Page 665: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/665.jpg)
DisplayingUser-FriendlyMessagesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 666: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/666.jpg)
MicrosoftEnterpriseLibrary5.0
NotifyingtheUser
WhenyouusetheExceptionHandlingApplicationBlock,afrequentlyrequiredtaskistonotifytheuserwhenanexceptionoccurs.(Generally,thisshouldbecompletedafterthemessagehasbeenchangedtoonethatissuitablefortheparticularuser.Formoreinformation,seeDisplayingUser-FriendlyMessages.)Dependingontheapplicationtype,youcandothisusingaWindowsFormsdialogboxoraWebpage.Whenanexceptioncannotbehandledwithintheapplication,theusermustreceiveanotificationthatanerroroccurred,alongwithsomeguidanceofwhatheorsheshoulddonext.
![Page 667: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/667.jpg)
TypicalGoals
![Page 668: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/668.jpg)
Solution
![Page 669: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/669.jpg)
NotifyingtheUser
![Page 670: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/670.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 671: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/671.jpg)
MicrosoftEnterpriseLibrary5.0
AssistingSupportStaff
WhenyouusetheExceptionHandlingApplicationBlock,afrequentlyrequiredtaskistoallowsupportstafftoaccessdetailedinformationtoassistuserswhenexceptionsoccur.Whenanexceptionoccursthatcannotbehandled,usersaregenerallyshownafriendlyerrormessage.Usersmayhavetocallsupportstaff,andsupportstaffmayneedmorethantheusererrormessagetodeterminewhatwentwrongandhowtofixtheproblem.Thisscenariodemonstrateshowtomatchtheuser'serrormessagewiththedetailedexceptionlogthatcanbeaccessedbysupportstaff.
![Page 672: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/672.jpg)
TypicalGoals
![Page 673: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/673.jpg)
Solution
![Page 674: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/674.jpg)
AssistingSupportStaff
![Page 675: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/675.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 676: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/676.jpg)
MicrosoftEnterpriseLibrary5.0
ShieldingExceptionsatWCFServiceBoundaries
InWindowsCommunicationFoundation(WCF),topreventdetailsoftheserviceimplementationfromescapingthesecureboundaryoftheservice,unknownexceptionsshouldnotbesenttotheclientapplication.ThisiscontrolledthroughtheincludeExceptionDetailInFaultsattributeinthe<serviceDebug>elementintheWCFconfiguration.Toenableexceptionshielding,thisattributemustbesettofalse.Ifnotspecifiedintheconfigurationfile,thispropertyissettofalse.
Note:TheincludeExceptionDetailInFaultsconfigurationsettingisusedonlyforunknownorunhandledexceptions.Itdoesnothaveanyeffectonknownexceptions,wheretheoperationhasaFaultContractwiththeknownfaulttypeandtheoperationthrowsaFaultException<knownFault>whereknownFaultisinthefaultcontract.
ExceptionshieldinghelpspreventaWebservicefromdisclosinginformationabouttheinternalimplementationoftheservicewhenanexceptionoccurs.Thefollowingforcesexplainwhyyoushoulduseexceptionshielding:
Exceptiondetailsmaycontaincluesthatanattackercanusetoexploitresourcesusedbythesystem.Informationrelatedtoanticipatedexceptionsneedstobereturnedtotheclientapplication.ExceptionsthatoccurwithinaWebserviceshouldbeloggedtosupporttroubleshooting.
Onlyexceptionsthathavebeensanitizedoraresafebydesignshouldbereturnedtotheclientapplication.Exceptionsthataresafebydesigndonotcontainsensitiveinformationintheexceptionmessageandtheydonotcontainadetailedstacktrace,eitherofwhichmightrevealsensitiveinformationabouttheWebservice'sinnerworkings.YoushouldusetheExceptionShieldingpatterntosanitizeunsafeexceptionsbyreplacingthemwithexceptionsthataresafebydesign.
![Page 677: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/677.jpg)
TheExceptionHandlingApplicationBlockincludessupportforexceptionshieldingatWCFserviceboundaries.Thissupportconsistsofthefollowing:
TheExceptionShieldingAttribute,whichisusedtoassociateanamedexceptionhandingpolicyconfiguredintheExceptionHandlingApplicationBlockwithaWCFserviceoperation.Formoreinformation,seethefollowingsectionUsingtheExceptionShieldingAttribute.TheFaultContractExceptionHandler,whichconvertsanexceptiontoaspecifictypeofFaultContractandmapsthedesiredpropertiesoftheexceptiontotheFaultContract.Formoreinformation,seethefollowingsectionUsingtheFaultContractExceptionHandler.
![Page 678: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/678.jpg)
UsingtheExceptionShieldingAttribute
![Page 679: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/679.jpg)
UsingtheFaultContractExceptionHandlerToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 680: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/680.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheExceptionHandlingApplicationBlock
TheExceptionHandlingApplicationBlockisdesignedtoachievethefollowinggoals:
Encapsulatethelogicusedtoperformthemostcommonexceptionhandlingtasksintominimalapplicationcode.Relievedevelopersoftherequirementtowriteduplicatecodeandcustomcodeforcommonexceptionhandlingtasks.Allowexceptionhandlingpoliciestobechangedaftertheyhavebeendeployedandtoensurethatchangeshappensimultaneouslyandconsistently.Incorporatebestpracticesforexceptionhandling,asdescribedintheDesignGuidelinesforExceptions.
![Page 681: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/681.jpg)
DesignHighlightsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 682: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/682.jpg)
MicrosoftEnterpriseLibrary5.0
DesigningforSimplifiedCatchBlocks
Commonexceptionhandlingbehavior,suchasloggingandreplacingexceptionstohidesensitiveinformation,typicallyrequiresmultiplelinesofcode.Updatingexception-handlingbehaviortoaccommodateachangeinanexceptionhandlingpolicyusuallyinvolvesupdatingmultiplefilesandlinesofcode.Thisprocesscanbeerror-prone,anditisdifficulttoensurethatpoliciesareupdatedconsistentlyacrossalllayersofanapplication.
TheExceptionHandlingApplicationBlocksimplifiesboththeexceptionhandlingcodeandtheprocessofupdatingthatcode.Itdoesthisbyassociatingexception-handlingbehaviorwithpolicynamessuchasDataAccessLayerPolicyandTrustBoundaryPolicy.Thebehaviorsrepresentedbypolicynamesarecontrolledexternally,intheconfigurationfortheapplication.Thismeansthatadeveloperneedstouseonlytwoelementstowritecodeinthecatchblockofanapplication:
AcalltotheHandleExceptionorProcessmethodthatpassesthepolicynameandtheexception.AcheckofthereturncodefromtheHandleExceptionmethod;ifitreturnstrue,theoriginalexceptionshouldbere-thrown.
![Page 683: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/683.jpg)
DesignImplications
![Page 684: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/684.jpg)
APISupportforPolicyNamesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 685: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/685.jpg)
MicrosoftEnterpriseLibrary5.0
DesigningforEncapsulationofBehaviorinReusableHandlers
TheExceptionHandlingApplicationBlockhelpsdeveloperstocreateexceptionhandlersthatrepresentcommonexceptionhandlingtasks.Thesehandlers,aswellascombinationsofhandlers,canbeusedbydifferentpolicies.
![Page 686: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/686.jpg)
DesignImplications
![Page 687: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/687.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 688: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/688.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingtheExceptionHandlingApplicationBlock
Initsoriginalstate,theExceptionHandlingApplicationBlockworkswellfortypicalexceptionhandlingscenarios,suchaslogginganexceptionmessage,wrappingoneexceptionwithanother,orreplacinganexceptionwithadifferentexception.However,theremaybetimeswhenyouhavetocustomizecertainbehaviorsoftheblocktobettersuityourapplication'sparticularrequirements.Therearetwowaystodothis.YoucanextendtheExceptionHandlingApplicationBlockusingthebuilt-inextensionpoints.Inaddition,youmaychoosemodifytheblockbymakingchangestoitssourcecode.
YouextendtheExceptionHandlingApplicationBlockthroughdesignatedextensionpoints.Typically,thesearecustomclasseswrittenbyyouthatimplementaparticularinterfaceorderivefromanabstractclass.Becausethesecustomclassesexistinyourapplicationspace,youdonothavetomodifyorrebuildtheExceptionHandlingApplicationBlock;instead,youcandesignateyourextensionsthroughconfigurationsettings.
Youcanextendtheblockbyaddinganewtypeofexceptionhandlerorexceptionformatter.Thefollowingtableliststheinterfacesandbaseclassesthatyoucanusetoextendtheblock.
CustomProviderorExtension InterfaceorBaseClass
ExceptionHandler IExceptionHandler
ExceptionFormatter ExceptionFormatter
FormoredetailsofhowtoextendandmodifytheblockandEnterpriseLibrary,seethefollowingtopics:
AddingaNewExceptionHandlerAddingaNewExceptionFormatterCreatingCustomProvidersforEnterpriseLibraryExtendingandModifyingEnterpriseLibrary
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.
![Page 689: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/689.jpg)
Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 690: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/690.jpg)
MicrosoftEnterpriseLibrary5.0
AddingaNewExceptionHandler
Toaddanewexceptionhandler,youmustfirstcreateanewclassthatimplementstheIExceptionHandlerinterface.Afteryoucompilethenewclassintoanassembly,youcanusetheEnterpriseLibraryConfigurationConsoletoaddittotheExceptionHandlingApplicationBlockconfigurationforyourapplication.
![Page 691: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/691.jpg)
CreatingaNewExceptionHandlerClassToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 692: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/692.jpg)
MicrosoftEnterpriseLibrary5.0
AddingaNewExceptionFormatter
Toaddanewexceptionformatter,youmustcreateanewexceptionclassthatderivesfromtheExceptionFormatterclass.YournewclasscanderivedirectlyfromExceptionFormatterorfromoneoftheexceptionformattersthatshipwiththeExceptionHandlingApplicationBlock.TheblockincludestheclassesTextExceptionFormatterandXmlExceptionFormatter,bothofwhichderivefromtheExceptionFormatterclass.
ExceptionformattersmustincludethehandlinginstanceID,HandlingInstanceId.ThehandlinginstanceIDvalueisgeneratedoneachexceptionhandlingrequest.EachindividualexceptionformatterhandlesthehandlinginstanceIDasappropriateforthatformatter.TheXmlExceptionFormatteraddsitasanattributeofthetop-levelExceptionelement,whiletheTextFormatteraddsitasthefirstlineoftext.AHandlingInstanceIdequaltoGuid.Emptycanbeignored.
TheloggingexceptionhandlerdoesnotaddtheexceptionhandlingIDtothemessagetolog.TheformatterhandlestheID.ExceptionFormattertypesusedwiththeLoggingexceptionhandlermustimplementaconstructorwithparametersoftypeTextWriter,Exception,andGuid,asshowninthefollowingcode.C#
publicMyExceptionFormatter(TextWriterwriter,Exceptionex,GuidhandlingInstanceId)
:base(ex,handlingInstanceId)
{
...
}
VisualBasic
PublicSubNew(writerAsTextWriter,exAsException,handlingInstanceIdAsGuid)
MyBase.New(ex,handlingInstanceId)
...
EndSub
![Page 693: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/693.jpg)
Note:IfyouhavecustomformattersdesignedforusewithversionsofEnterpriseLibrarypriortoversion4.1,youmustupdatethemsothatthehandlinginstanceIDisnotlost.
![Page 694: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/694.jpg)
CreatingaNewExceptionFormatterClassToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 695: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/695.jpg)
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetomakesurethattheinitialdeploymentoftheExceptionHandlingApplicationBlockisplannedandmanagedandtomakesurethatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecideiftheywishtousetheinstrumentationexposedbytheblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheExceptionHandlingApplicationBlock,seethefollowingtopics:
ExceptionHandlingApplicationBlockPerformanceCountersExceptionHandlingApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 696: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/696.jpg)
MicrosoftEnterpriseLibrary5.0
ExceptionHandlingApplicationBlockPerformanceCounters
ThefollowingtabledescribestheExceptionHandlingApplicationBlockperformancecounters.
PerformanceCounterName
Description
ExceptionHandlersExecuted/sec
Therateatwhichexceptionhandlerswereexecuted.
ExceptionsHandled/sec Therateatwhichexceptionswerehandled.
TotalExceptionsHandled Thetotalnumberofexceptionshandled.
TotalExceptionsHandlersExecuted
Thetotalnumberofexceptionhandlersthatwereexecuted.
Aratecountersamplesanincreasingcountofeventsovertimeanddividesthevaluesbythechangeintimetodisplayarateofactivity.Formoreinformationaboutperformancecounters,seeOverviewofPerformanceMonitoringinthe.NETFrameworkClassLibrary.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 697: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/697.jpg)
MicrosoftEnterpriseLibrary5.0
ExceptionHandlingApplicationBlockEventLogEntries
TheExceptionHandlingApplicationBlockisinstrumentedtologentriestotheapplicationeventlogforavarietyofevents.ThistopicliststheExceptionHandlingApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
![Page 698: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/698.jpg)
ExceptionHandlingErrorEvent
![Page 699: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/699.jpg)
ConfigurationErrorEvent
![Page 700: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/700.jpg)
InternalErrorEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 701: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/701.jpg)
MicrosoftEnterpriseLibrary5.0
TheLoggingApplicationBlock
Developersfrequentlywriteapplicationsthatrequireloggingfunctionality.Typically,theseapplicationsformatandloginformationinresponsetoapplicationevents.Forexample,theymayberequiredtologinformationinresponsetounexpectedconditions,suchasanapplicationexception,orfailuretoconnecttoadatabase.Developersalsowritecodetotraceapplicationflowthroughcomponentsduringtheexecutionofanapplicationusecaseorscenario.Inaddition,applicationsoftenneedtowriteinformationlocallyandoveranetwork.Insomecases,youmayneedtocollateeventsfrommultiplesourcesintoasinglelocation.
TheEnterpriseLibraryLoggingApplicationBlocksimplifiestheimplementationofcommonloggingfunctions.YoucanusetheLoggingApplicationBlocktowriteinformationtoavarietyoflocations:
TheeventlogAne-mailmessageAdatabaseAmessagequeueAtextfileAWindows®ManagementInstrumentation(WMI)eventCustomlocationsusingapplicationblockextensionpoints
ThissectionincludesthefollowingtopicsthatwillhelpyoutounderstandandusetheLoggingApplicationBlock:
WhatDoestheLoggingBlockDo?Thistopicprovidesabriefoverviewthatwillhelpyoutounderstandwhattheblockcando,andexplainssomeoftheconceptsandfeaturesitincorporates.Italsoprovidesasimpleexampleofhowtowritecodetousetheblock.WhenShouldIUsetheLoggingBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andanyalternativetechniquesyoumayconsider.Italsoprovidesdetailsofanylimitationsoftheblockthatmayaffectyourdecisiontouseit.DevelopingApplicationsUsingtheLoggingApplicationBlock.ThistopicexplainshowtousetheLoggingApplicationBlockinyour
![Page 702: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/702.jpg)
applications.Itshowshowtoconfiguretheapplicationblocktoperformcommontasksandhowtoaddapplicationcodetotheapplicationblockwhererequired.KeyScenarios.Thistopicdemonstrateshowtousetheapplicationblocktoperformthemostcommonloggingoperations.DesignoftheLoggingApplicationBlock.Thistopicexplainsthedecisionsthatwentintodesigningtheapplicationblockandtherationalebehindthosedecisions.ExtendingandModifyingtheLoggingApplicationBlock.Thistopicexplainshowtoextendtheapplicationblockbycreatingyourowncustomtracelisteners,logformatters,andlogfilters;andexplainshowtomodifythesourcecode.DeploymentandOperations.Thistopicexplainshowtodeployandupdatetheapplicationblock'sassembliesandalsocontainsinformationabouttheinstrumentationintheblock.
![Page 703: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/703.jpg)
MoreInformationFormoreinformationaboutloggingandmanagingothercrosscuttingconcerns,seethefollowingpatterns&practicesguides:
MicrosoftApplicationArchitectureGuide,2ndEditionDesignGuidelinesforExceptions
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 704: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/704.jpg)
MicrosoftEnterpriseLibrary5.0
WhatDoestheLoggingBlockDo?
Althoughtheprocessofcreatingandwritinglogentriesisrelativelysimple,thenumberofoptionsavailable(suchasthemanyloggingtargetsandtheabilitytofilterentries)meansthattheunderlyingstructureoftheblockandtheoptionsavailableforusingitcanseemcomplex.Thefollowingschematicshowshowthemaintypesofobjectintheblockworktogethertoprovideflexibilitywhencreatingandwritinglogentries.
![Page 705: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/705.jpg)
Thefivemaintypesofobjectsare:LogWriter.Thelogwriteristhemainentrypointforcreatinglogentriesandwritingthemtoyourchosenloggingtargets.Itcreatesaninstanceofalogentrycontainingtheinformationtobelogged,andinteractswiththeotherobjectsthatfilterthelogentry,assignittooneormorecategories,formatit,anddispatchittotheappropriatetargets.LogFilters.Logfilterscanblockorallowalogentrybasedonanumberoffeatures.Eachlogentryisassignedtooneormorecategories(thedefaultistheGeneralcategory),andthecategorylogfiltercanusethesecategoriestopassorblockalogentry.Inaddition,twospeciallogfilterscanblockalllogging,orblocklogentrieswithaprioritylowerthanaspecifiedvalue.Youdefinethecategories,priorities,andthesettingsforthelogfiltersintheconfigurationfortheblock.TraceSources.Tracesourcesareeffectivelyasetofbucketsintowhichtheblockplacesalllogentriesthathavenotbeenblockedbyalogfilter.Youusethesebucketstodefinewherelogentrieswillbedispatchedto—youcanthinkofthemasbeingthesourceofthelogentriesthatwillactuallybedispatchedtothetargetdestinations.Therearetwobasictypesoftracesources:
Thereisatracesourceforeachcategoryyoudefineintheconfigurationoftheblock.ThesearecalledCategorySources.Therearethreebuilt-intracesources:onethatreceivesalllogentries,onethatreceiveslogentrieswhenanerroroccursduringprocessingordispatchingofthelogentry,andonethatreceivesalllogentriesthatdonotmatchanyconfiguredcategory.ThesearecalledSpecialSources.
TraceListeners.Tracelistenersrepresentthetargetsforyourlogentries,andyouconfigureoneforeachtypeoftarget(suchastheWindows®EventLog,adiskfile,andane-mailmessage)towhichyouwanttosendthelogentries.Tracelistenerslistenforlogentriesarrivinginthetracesourcebuckets,formateachlogentryasrequired,anddispatchittothetargetconfiguredforthattracesource.Yourconfigurationmapseachtracesource(eachcategorysourceyoudefineplusthethreespecialsources)tooneormoretracelisteners.Theimportantpointtonotehereisthatthisallowsyoutodispatcheachlog
![Page 706: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/706.jpg)
entrytozero,one,ormoretargets(suchassendingitase-mailaswellaswritingittotheWindowsEventLog).LogFormatters.Eachtracelisteneryouaddtoyourconfigurationcanusealogformattertoconvertthedatainthelogentryfromaseriesofpropertiesintoformatsuitableforsendingtothelogtarget.Theblockcontainsatextformatterthatyoucanconfigurewithtracelistenersthatdispatchlogentriestotargetssuchasdiskfiles,e-mail,orWindowsEventLog;andabinaryformatterthatserializesthelogentrydataintoaformatsuitablefortransmissiontotargetssuchasWindowsMessageQueuing(MSMQ).Thetextformatterisconfigurablesothatyoucanmodifytheformatandcontentofthetextmessage,includingusingplaceholdersforthevaluesofthepropertiesofthelogentry.
![Page 707: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/707.jpg)
TheLoggingProcessSequence
![Page 708: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/708.jpg)
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 709: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/709.jpg)
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheLoggingBlock?
IfyourapplicationshavearequirementtologinformationtoWindowsEventLog,e-mail,adatabase,amessagequeue,WindowsManagementInstrumentation(WMI),orafile,youshouldconsiderusingtheLoggingApplicationBlocktoprovidethisfunctionality.Inparticular,theLoggingApplicationBlockisusefulifyouneedtofilterloggingmessagesbasedoncategoryorpriority,ifyouneedtoformatthemessages,orifyouneedtochangethedestinationofthemessagewithoutchangingtheapplicationcode.TheLoggingApplicationBlockisalsodesignedtobeextensibleandincludesthefacilitytocreatecustomformattersandtracelisteners,whichyoucanadapttomeetyourapplication'sloggingrequirements.
![Page 710: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/710.jpg)
ScenariosfortheLoggingApplicationBlock
![Page 711: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/711.jpg)
BenefitsoftheLoggingApplicationBlock
![Page 712: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/712.jpg)
LimitationsoftheLoggingApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 713: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/713.jpg)
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheLoggingApplicationBlock
ThistopicdescribeshowtodevelopapplicationsusingtheLoggingApplicationBlock.Itexplainshowtoconfiguretheapplicationblocktoperformparticulartasksandhowtousetheapplicationblockaccordingtoparticularapplicationscenariossuchaspopulatingandraisingeventsfromcode.Itincludesthefollowingtopics:
EnteringConfigurationInformationUsingtheDistributorServiceAddingApplicationCode
Ifyouwanttodeliverlogentriesatacentrallocationforprocessing,youcanusetheLoggingApplicationBlockwithMessageQueuing(alsoknownasMSMQ)toallowyoutodothis.Byconfiguringmultipleapplicationstousethesamemessagequeue,youcandeliverallthelogentriestooneplace.FordetailsofhowtoinstallandconfiguretheLoggingApplicationBlockinthisscenario,seeUsingtheDistributorService.
IfyouareusingtheLoggingApplicationBlockwithaWindowsCommunicationFoundation(WCF)application,youmustconfigureintegrationwithWCF.Fordetails,seeConfiguringWCFIntegrationTraceListeners.
Allapplicationblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompileit.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Thistopicassumesyouareusingtheapplicationblockinitsoriginalstate,withoutextendingit.(Tolearnhowtoaddfunctionality,seeExtendingandModifyingtheLoggingApplicationBlock.)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 714: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/714.jpg)
MicrosoftEnterpriseLibrary5.0
EnteringConfigurationInformation
ThissectionexplainshowtoconfiguretheLoggingApplicationBlock.Foranoverviewandexampleofconfiguringtheblock,seeConfigurationOverview.FordetailsoftheschemafortheLoggingApplicationBlockconfiguration,seeSourceSchemafortheLoggingApplicationBlock.Youcanalsoconfiguretheblockincodebyusinganalternateconfigurationsource.Formoreinformation,seeAdvancedConfigurationScenariosandUsingtheFluentConfigurationAPI.
Note:RuntimechangestotheconfigurationoftheLoggingApplicationBlockareautomaticallydetectedafterashortperiod,andtheloggingstackisupdated.However,youcannotmodifytheloggingstackatruntimethroughcode.Fordetailsofusingconfigurationmechanismsthatyoucanupdateatruntime,seeUpdatingConfigurationSettingsatRunTime.
ToaddtheLoggingApplicationBlock1. Opentheconfigurationfile.Formoreinformation,seeConfiguring
EnterpriseLibrary.2. OpentheBlocksmenuandthenclickAddLoggingSettings.3. Thisaddsadefaultgeneralcategory,thethreestandardspecial
categories,adefaulteventloglistener,andadefaulttextformattertotheconfiguration.
4. ClickthechevronexpanderarrowintheLoggingSettingssectiontoviewallsettingsforthissection.
5. Clicktheexpanderarrowattheleftofthegeneralcategory,thespecialcategories,theeventloglistener,orthetextformattertoviewandsettheirpropertiesasdescribedinthefollowingtopics.
AfteryouaddtheLoggingApplicationBlocktotheapplicationconfiguration,youcanconfiguresomeorallofthefollowingfeatures.Youshouldperformthesetasksinthefollowingorder:
ConfiguringTraceListenersConfiguringFormatters
![Page 715: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/715.jpg)
ConfiguringTraceSourceCategoriesConfiguringLoggingFiltersConfiguringtheApplicationBlock
![Page 716: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/716.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 717: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/717.jpg)
MicrosoftEnterpriseLibrary5.0
ConfigurationOverview
TounderstandhowyouconfigureandusetheLoggingApplicationBlock,youmustbefamiliarwiththewaytheblockprocesseslogentries.ThetopicWhatDoestheLoggingBlockDo?providesasimplifiedoverviewoftheprocessandwillhelpyouwhenyoucometoconfiguretheblock.
ThefollowingstepsillustratethegeneralprocessforconfiguringtheLoggingApplicationBlock.ItassumesyouwanttousetwocategoriesnamedDevandOperations.
1. AddthetracelistenersyouwanttousetooutputthelogginginformationbyclickingontheplussigniconintheLoggingTargetListenerssectionoftheLoggingSettingsconfigurationpaneandclickingAddLoggingTargetListenerstodisplaythelistoflisteners.Whenyouselectalistener,itisaddedtotheLoggingTargetListenerssectionwhereyoucanthensetitsproperties.
2. AddtheformattersyouwantthetracelistenerstousetoformattheoutputbyclickingontheplussigniconintheLogMessageFormatterssectionoftheLoggingSettingsconfigurationpaneandclickingAddLogMessageFormatterstodisplaythelistofformatters.Whenyouselectaformatter,itisaddedtotheLogMessageFormatterssectionwhereyoucanthensetitsproperties.
![Page 718: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/718.jpg)
3. SettheFormatterNamepropertyofeachtracelistenerintheLoggingTargetListenerssectionoftheLoggingSettingsconfigurationpanetospecifytheappropriateformatter.
4. AddthecategoryfiltersyouwanttousetotheCategoriessectionoftheLoggingSettingsconfigurationpanebyclickingontheplussigniconintheCategoriessectionoftheLoggingSettingsconfigurationpaneandclickingAddCategory.AnewcategoryitemisaddedtotheCategoriessectionwhereyoucanthensetitsproperties.Clickonitspropertyexpanderarrowifthepropertiesarenotvisible.
5. AddareferencetoeachofthetracelistenersyouwanttousetooutputthelogginginformationtoeachofthecategoriesyoucreatedintheCategoriessectionoftheLoggingSettingsconfigurationbyclickingtheListenerspropertyplussigniconandselectingaconfiguredloggingtargetlistener.EachentryhereisareferencetooneofthetracelistenersyoupreviouslyconfiguredintheTraceListenerssection.Youcanaddmorethanonetracelistenerreferencetoeachcategoryfilteryoucreate.Forexample,youcouldspecifythefollowing:
AlogentrycontainingthecategorynameDevwillgotoaneventlogtracelistener(sothatitappearsinWindowsEventLog)AlogentrycontainingthecategorynameOperationswillgotoane-mailtracelistenerandtoanXMLtracelistener.
6. AddareferencetoeachofthetracelistenersyouwanttousetooutputthelogginginformationtotheappropriatesubsectionsoftheSpecialCategoriessectionoftheLoggingSettingsconfigurationpane.Forexample,youmaywanttodothefollowing:
Sendthelogentrytoane-mailtracelistenerwhenanerroroccurswithintheloggingsystembyaddingareferencetothistracelistenertotheLoggingErrors&Warningssection.Sendthelogentrytoaneventlogtracelistenerwhenthelogentrydoesnotmatchanyconfiguredcategorybyaddinga
![Page 719: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/719.jpg)
referencetothistracelistenertotheUnprocessedCategorysection.Sendalllogentries,irrespectiveofcategoryorcontent,toaFlatFiletracelistenerbyaddingareferencetothistracelistenertotheAllEventssection.
7. Settheremainingpropertiesforeachcategoryorspecialfilter.Specifythelogginglevel,suchasCritical,Error,Warning,orAll,bysettingtheMinimumSeveritypropertyforeachcategoryfilter.
8. Finally,addanylogfiltersyouwanttousetotheLoggingFilterssectionoftheLoggingSettingsconfigurationpanebyclickingontheplussigniconintheLoggingFilterssectionoftheLoggingSettingsconfigurationpaneandclickingAddLoggingFilters.ThefiltertypeyouselectisaddedtotheLoggingFilterssectionwhereyoucanthensetitsproperties.Clickonitspropertyexpanderarrowifthepropertiesarenotvisible.Forexample,youcoulduseacategoryfiltertoblockallloggingoperationsexceptthosethatspecifyoneofthetwocategoriesnamedDevorOperations.
![Page 720: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/720.jpg)
ForspecificdetailsofhowtoconfigureeachsectionoftheLoggingApplicationBlockconfiguration,seeEnteringConfigurationInformation.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 721: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/721.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringTraceListeners
Tracelistenersreceivelogentriesandwritethemtotheappropriatedestinations.ThefollowingproceduredescribeshowtoconfigurethetracelistenerssuppliedwithEnterpriseLibraryandcustomtracelistenersthatyoucreate.ThereisalsoaspecificprocedureforconfiguringthetwotracelistenersthatarerequiredforintegrationwithWCF.Formoredetailsofthisprocedure,seeConfiguringWCFIntegrationTraceListeners.
Note:Tracelistenerlogshavevulnerabilitiesandshouldbeprotectedasappropriate,dependingonwhetherthetracelistenerwriteslogentriestoafile,databaseorMSMQmessagequeue.
Fortracelistenersthatwritelogentriestofilesyoushouldprotectthelogsbyusingaccesscontrollists.ThisincludesFlatFile,Rollingflatfile,WMIandXMLtracelistenerlogs.
Fortracelistenersthatwritelogentriestodatabasesyoushouldprotectaccesstologsbyusingusernamesandpasswords.Thisincludesthedatabasetracelistener.
FortracelistenersthatwritelogentriestoMSMQmessagequeuesyoushouldallowonlyauthorizeduserstoreadinformationfromMSMQ.ProtectthequeuewithrelevantaccesscontrollistsandfollowanysecurityconsiderationsspecifictoMSMQ.Thisincludesthemessagequeuingtracelistener.
![Page 722: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/722.jpg)
ConfiguringtheBuilt-inTraceListeners
![Page 723: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/723.jpg)
ConfiguringCustomTraceListenersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 724: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/724.jpg)
MicrosoftEnterpriseLibrary5.0
TraceListenerProperties
Thesetablesexplainthepropertiesforthedifferenttracelisteners.Therearetablesforthefollowingtracelisteners:
DatabaseTraceListener.Thistracelistenerwritesformattedlogentriestoadatabase.E-mailTraceListener.Thistracelistenersendslogentriesase-mailmessages.EventLogTraceListener.ThistracelistenerformatslogentriesandwritesthemtoWindowsEventLog.FlatFileTraceListener.Thistracelistenerwriteslogentriestoatextfile.MessageQueuingTraceListener.Thistracelistenerwriteslogentriestoamessagequeue.RollingFlatFileTraceListener.Thistracelistenercreatesanewlogfiledependingonthecurrentlogfileageand/orsize.SystemDiagnosticsTraceListener.Thisisoneofthe.NETFrameworktracelistenerssuchastheConsoleTraceListener.WMITraceListener.ThistracelistenerraisesaWMImanagementeventforeachlogentryreceived.XMLTraceListener.ThistracelistenerisusedtooutputlogmessagestoanXMLformattedfile.
![Page 725: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/725.jpg)
DatabaseTraceListenerThefollowingtableliststhepropertiesthatyoucansetwhenyouaddaDatabaseTraceListener.
Property Description
AddCategoryProcedure
Thenameofthestoredprocedurethataddsacategory.ThedefaultisAddCategory.Thisisrequired.
DatabaseInstance
ThenameofthedatabaseinstancetouseasconfiguredintheDataSettingssectionoftheconfiguration.Thisisrequired.
SeverityFilter
Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
Formatter Theformattertousewiththistracelistener.Selectonefromthedrop-downlist.Thedefaultisnone.Thisisoptional.
Name Thenameofthetracelistener.ThedefaultisDatabaseTraceListener.Thisisrequired.
TraceOutputOptions
Apropertyusedbytracelistenersthatdonotoutputtoatextformattertodeterminewhichoptions,orelements,shouldbeincludedinthetraceoutput.PossiblevaluesareCallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
WriteToLogProcedure
Thenameofthestoredprocedurethatwritesthelogentries.ThedefaultisWriteLog.Thisisrequired.
![Page 726: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/726.jpg)
EmailTraceListenerThefollowingtableliststhepropertiesthatyoucansetwhenyouaddane-mailtracelistener.
Property Description
AuthenticationMode
AvaluefromtheEmailAuthenticationModeenumerationthatspecifieshowthelistenerwillauthenticatetheuser.ValidvaluesareNone,WindowsCredentials,andUserNameAndPassword.
SeverityFilter Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
FormatterName
Theformattertousewiththistracelistener.Selectonefromthedrop-downlist.Thedefaultisnone.Thisisoptional.
FromAddress Theaddresswherethelogentryoriginated.Thedefaultisfrom@example.com.Thisisrequired.
Name Thenameofthetracelistener.ThedefaultisEmailTraceListener.Thisisrequired.
AuthenticationPassword
Passwordwhenauthenticatingwithusernameandpassword.
SmtpPort TheSMTPportthatreceivese-mailmessages.Thedefaultis25.Thisisoptional.
SmtpServer TheSMTPserverusedtosende-mailmessages.Thedefaultis127.0.0.1.Thisisoptional.
SubjectLineSuffix
Thesubjectlinesuffix.Thisisoptional.
SubjectLine Thesubjectlineprefix.Thisisoptional.
![Page 727: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/727.jpg)
Prefix
ToAddress Theaddresswherethelogentryissent.Thedefaultisto@example.com.Thisisrequired.
TraceOutputOptions
Tracelistenersthatdonotoutputtoatextformatterusethispropertytodeterminewhichoptions,orelements,shouldbeincludedinthetraceoutput.Possiblevaluesare:CallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
AuthenticationUserName
Usernamewhenauthenticatingwithusernameandpassword.
UseSSL Specifiesifthee-mailtracelistenershoulduseSSLwhenconnectingtothemailserver.SettoTruetouseSSLtoconnect,orFalsetouseanunencryptedconnection.ThedefaultisFalse
Note:Theconfigurationfilesarenotencryptedbydefault.Aconfigurationfilemaycontainsensitiveinformationaboutconnectionstrings,userIDs,passwords,databaseservers,andcatalogs.Youshouldprotectthisinformationagainstunauthorizedread/writeoperationsbyusingencryptiontechniques.Forinformationabouthowtoencryptconfigurationfiles,seeEncryptingConfigurationDataandConfiguringEnterpriseLibrary.
Inadditiontothisproblem,e-mailmessagesexchangedwithaSMTPservercouldbeinterceptedwhileintransitbyamalicioususerrunninganetworksnifferormonitoringapplication.YoucanmitigatethisproblembysupportingTransportLayerSecurityorS/Mimewithencryptionofthee-mailmessages.
![Page 728: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/728.jpg)
FlatFileTraceListenerThefollowingtableliststhepropertiesthatyoucansetwhenyouaddaflatfiletracelistener.
Property Description
FileName Thenameofthefilewhereentriesarewritten.Thedefaultnameistrace.log.Thisisarequiredvalue.Itcanincludeenvironmentvariablessuchas%WINDIR%,%TEMP%,and%USERPROFILE%.
SeverityFilter
Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
MessageFooter
Additionalinformationcontainedinthefilefooter.Thedefaultis"----------------------------------------."Thisisoptional.
FormatterName
Theformattertousewiththistracelistener.Selectonefromthedrop-downlist.Thedefaultisnone.Thisisoptional.
MessageHeader
Additionalinformationcontainedinthefileheader.Thedefaultis"----------------------------------------."Thisisoptional.
Name Thenameofthetracelistener.ThedefaultisFlatFileTraceListener.Thisisrequired.
TraceOutputOptions
Tracelistenersthatdonotoutputtoatextformatterusethispropertytodeterminewhichoptions,orelements,shouldbeincludedinthetraceoutput.Possiblevaluesare:CallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
Note:
![Page 729: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/729.jpg)
IfthefileyouspecifyfortheFlatFileTraceListenerisread-only,thetracelistenerdoesnotwritethedatatothefileandnoexceptionoccurs.Makesurethatthefileattributesaresettoread/write.
WhenyouusetheFlatFileTraceListenerclasstowriteloginformationtoafile,theblocklocksthefileuntiltheapplicationcloses.Itispossibletoopenandreadthefile,butyoucannotmoveordeletethelogfileuntilyouclosetheapplication.
![Page 730: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/730.jpg)
EventLogTraceListenerThefollowingtableliststhepropertiesthatyoucansetwhenyouaddaneventlogtracelistener.
Property Description
SeverityFilter
Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
FormatterName
Theformattertousewiththistracelistener.Selectonefromthedrop-downlist.Thedefaultisnone.Thisisoptional.
LogName Thenameoftheeventlogwhereentriesarewritten.ThedefaultisApplication.Thisisoptional.
MachineName
Thenameofthecomputeronwhichtowritelogentries.Thisisoptional.
Name Thenameofthetracelistener.ThedefaultisEventLogTraceListener.Thisisrequired.
SourceName
Thesourcenametousewhenwritingtothelog.ThedefaultisEnterpriseLibraryLogging.Thisisrequired.
TraceOutputOptions
Tracelistenersthatdonotoutputtoatextformatterusethispropertytodeterminewhichoptions,orelements,shouldbeincludedinthetraceoutput.Possiblevaluesare:CallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
![Page 731: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/731.jpg)
MessageQueuingTraceListenerThefollowingtableliststhepropertiesthatyoucansetwhenyouaddaMessageQueuing(MSMQ)TraceListener.
Property Description
SeverityFilter Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
FormatterName
Theformattertousewiththistracelistener.Selectonefromthedrop-downlist.Thismustbethebinaryformatterwhenyouusethislistenerwiththemessagequeuingdistributorservice.Thisisoptional.
MessagePriority
Setsthepriorityofalogentry.Thisdeterminesitsprioritywhilethelogentryisintransitandwhenitisinsertedintoitsdestinationqueue.PossiblevaluesareAboveNormal,High,Highest,Low,Lowest,Normal,VeryHigh,andVeryLow.ItappliestotheMsmqTraceListenerclass.ThedefaultisNormal.Thisisoptional.
Name Thenameofthetracelistener.ThedefaultisMessageQueuingTraceListener.
QueuePath ThepathtothequeuethattheMsmqTraceListenerinstanceuses.Thisattributeisamessagequeuingpath,anditappliestotheMsmqTraceListenerclass.Thedefaultis.\Private$\myQueue.Thisisrequired.
Recoverable Specifieswhetherthelogentryisguaranteedtobedeliveredifthereisacomputerfailureornetworkproblem.ThedefaultisFalse.Thisisoptional.
TimeToBeReceived
Thetotaltimeforalogentrytobereceivedbythedestinationqueue.Thedefaultis49710.06:28:15.Thisisoptional.
![Page 732: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/732.jpg)
TimeToReachQueue
Themaximumtimeforthelogentrytoreachthequeue.Thedefaultis49710.06:28:15.Thisisoptional.
TraceOutputOptions
Attachesadditionalinformationtoplatform-providedtracelisteneroutputforlistenersthatdonotoutputtoatextformatter.PossiblevaluesareCallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
TransactionType
ThetypeofaMessageQueuingtransaction.PossiblevaluesareAutomatic,None,andSingle.ItappliestotheMsmqTraceListenerclass.ThedefaultisNone.Thisisoptional.
UseAuthentication
Specifieswhetherthemessagewas(ormustbe)authenticatedbeforebeingsent.ThedefaultisFalse.Thisisoptional.
UseDeadLetterQueue
Specifieswhetheracopyofamessagethatcouldnotbedeliveredshouldbesenttoadead-letterqueue.ThedefaultisFalse.Thisisoptional.
UseEncryption
Specifieswhethertomakethemessageprivate.ThedefaultisFalse.Thisisoptional.
![Page 733: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/733.jpg)
RollingFlatFileTraceListenerThefollowingtableliststhepropertiesthatyoucansetwhenyouaddarollingflatfiletracelistener.Thistracelistenerallowsyoutocontrolthesizeandageofalogfile.
Property Description
FileName Thisisthenameoftherollingflatfile.Thisisarequiredvalue.Itcanincludeenvironmentvariablessuchas%WINDIR%,%TEMP%,and%USERPROFILE%.IfyoualsosettheMaxArchivedFilesproperty,SeetheadviceonchoosingafilenameinthefollowingRemarkssection.
SeverityFilter
Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
MessageFooter
Additionalinformationcontainedinthefilefooter.Thedefaultis"----------------------------------------."Thisisoptional.
FormatterName
Theformattertousewiththistracelistener.Selectonefromthedrop-downlist.Thedefaultisnone.Thisisoptional.
MessageHeader
Additionalinformationcontainedinthefileheader.Thedefaultis"----------------------------------------."Thisisoptional.
MaxArchivedFiles
Themaximumnumberoflogfilestoretain.Whensettoanintegervalue,thetracelistenerwillpurgeoldfilesbasedonthefilecreationdatewhenthenumberexceedsthespecifiedvalue.SeethenoteinthefollowingRemarkssectionifyousetthisproperty.
Name Thisisthenameofthetracelistener.ThedefaultisRollingFlatFileTraceListener.Thisisrequired.
FileExistsBehavior
Thispropertydetermineswhatoccurstoanexistingfilewhenitrollsover.IfyouselectIncrement,theapplicationblock
![Page 734: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/734.jpg)
createsanewfileandnamesitbyincrementingthetimestamp.IfyouselectOverwriteanddonotprovideavaluefortheTimestampPatternproperty,theexistingfileisoverwritten.
RollInterval
Thispropertydetermineswhenthelogfilerollsover.YoucanselectNone(thedefault),Midnight(inwhichcasethelogwillrolloveratmidnight),Minute,Hour,Day,Month,Week,orYear.Thisisoptional.
RollSizeKB
Thisisthemaximumsizethefilecanreach,inkilobytes,beforeitrollsover.Thisisoptional.
TimestampPattern
Thisisthedate/timeformatthatisappendedtothenewfilename(seetheRemarkssectionthatfollowsthistable).
TraceOutputOptions
Tracelistenersthatdonotoutputtoatextformatterusethispropertytodeterminewhichoptions,orelements,shouldbeincludedinthetraceoutput.Possiblevaluesare:CallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
![Page 735: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/735.jpg)
RemarksIfyousettheMaxArchivedFilesproperty,thistracelistenerwilldelete(purge)filesusingthefilenamepattern[file-name]*.file-extension.Therefore,itwilldeletealllogfilesforanytracelistenerthatmatchesthispatternwhenitpurgesarchivedlogfiles.Topreventthis,useavaluefortheFileNamepropertythatincludedanadditionalperiod.Forexample,use[file-name].[additional-name].file-extension.Youcancontroleitherthesizeofthefile,itsage,orboth.Forexample,ifyouspecifyinconfigurationaRollSizeKBvalueof5KBandaRollIntervalvalueofDay,thefilerollswhenitssizeexceeds5KBanditalsorollsattheendoftheday.IfyouselectIncrementfortheFileExistsBehavior,theapplicationblockcreatesanewfilewhentheexistingfilerollsover.Thefilenameincludesthecurrenttimestamp.Ifafilewiththisnamealreadyexists,theapplicationblockaddsanintegertotheendofthetimestampandincrementsituntilitcannotfindafilewiththatname.Forexample,assumethereisafilenamedmylog2007-01-10.logandthefilerollsoverwhilethattimestampisstillvalid.TheLoggingApplicationBlockwillthenlookforafilenamedmylog2007-01-10.1.log.Ifnosuchfileexists,itwillusethatfilenameforthenewfile.Ifthatfilealsoexists,itwillthenattempttolocatethelogwiththenextsequencenumbermylog2007-01-10.2.log.IfyouselectOverwritefortheFileExistsBehavior,theapplicationblockreplacestheexistingfilewithanewfilewhenthecurrentfilerollsover.However,ifyoualsosettheTimestampPatternproperty,theapplicationblockwillcreateanewfilewiththecurrenttimestampinsteadofreplacingtheexistingfile.If,forsomereason,itcannotoverwritethefile,itwillgenerateanameusingthesameprocessthatisusedwiththeIncrementvalue.RelativepathnamesresolvetoalocationthatisrelativetotheAppDomain.CurrentDomain.BaseDirectorydirectory.
![Page 736: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/736.jpg)
SystemDiagnosticsTraceListenerTheTraceListenerclassprovidestheabstractbaseclassfortracelistenersthatmonitortraceanddebugoutput.ThefollowingtableliststhepropertiesthatappearwhenyouaddaSystemDiagnosticsTraceListener.
Property Description
InitData Ifsupplied,thispropertyisusedwhentheapplicationblockconstructsatracelistener.Itisastringwhosemeaningdependsonthetypeoftracelistenerbeingconstructed.Forthe.NETFrameworktracelisteners,thestringhasthefollowingvalues:TextWriterTraceListener:filename;XmlWriterListener:filename;DelimitedLIstTraceListener:filename;ConsoleTraceListener:notapplicable;DefaultTraceListener:notapplicable;EventLogTraceListener:eventsourcename.IftheInitDatafieldisnotspecified,theblockusesthedefaultconstructor.IftheuserspecifiestheInitDatafieldforatracelistenerthatdoesnothaveaconstructoroverloadthatacceptsastring,anerroroccurs.Thisisoptional.
Name Thenameofthetracelistener.ThedefaultisSystemDiagnosticsTraceListener.Thisisrequired.
SeverityFilter
Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
TraceOutputOptions
Tracelistenersthatdonotoutputtoatextformatterusethispropertytodeterminewhichoptions,orelements,shouldbeincludedinthetraceoutput.Possiblevaluesare:CallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
TypeName
Thetypeofthetracelistener.Selectbyclickingtheellipsisbutton(...).ThisopenstheTypeSelector.Thisisrequired.
![Page 737: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/737.jpg)
Note:IfyouspecifyaSystemDiagnosticstracelistenerthatwritestoafileandthatfileisread-only,thetracelistenerdoesnotwritethedatatothefileandnoexceptionoccurs.Makesurethefileattributesaresettoread/write.
![Page 738: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/738.jpg)
WMITraceListenerTheWMItracelistenerisatracelistenerthatraisesaWMImanagementeventforeachlogentryitreceives.ThefollowingtableliststhepropertiesthatyoucansetwhenyouaddaWMITraceListener.
Property Description
SeverityFilter
Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
Name Thenameofthetracelistener.ThedefaultisWMITraceListener.Thisisrequired.
TraceOutputOptions
Tracelistenersthatdonotoutputtoatextformatterusethispropertytodeterminewhichoptions,orelements,shouldbeincludedinthetraceoutput.Possiblevaluesare:CallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
![Page 739: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/739.jpg)
XMLTraceListenerThefollowingtableliststhepropertiesthatyoucansetwhenyouaddanXMLTraceListener.
Property Description
FileName
ThisisthenameofthefilewherethetracelistenerwritesthedataitextractsfromanXmlLogEntryobject.Thisisarequiredvalue.Itcanincludeenvironmentvariablessuchas%WINDIR%,%TEMP%,and%USERPROFILE%.
SeverityFilter
Appliesafilterthatselectsthelevelofmessagethatitwilldetect.ThevalidvaluesareAll(thedefault),Off,Critical,Error,Warning,Information,Verbose,andActivityTracing.Thesettingeffectivelymeans"thespecifiedlevelandeverythingmoreimportant."Forexample,theWarningsettingwilldetectwarnings,errors,andcriticalevents.
Name Thisisthenameofthetracelistener.ThedefaultisXMLTraceListener.Thisisrequired.
TraceOutputOptions
Tracelistenersthatdonotoutputtoatextformatterusethispropertytodeterminewhichoptions,orelements,shouldbeincludedinthetraceoutput.Possiblevaluesare:CallStack,DateTime,LogicalOperationStack,None,ProcessId,ThreadId,andTimestamp.ThedefaultisNone.Foranexplanationofthesevalues,seeTraceOutputOptionsValues.Thisisoptional.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 740: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/740.jpg)
MicrosoftEnterpriseLibrary5.0
TraceOutputOptionsValues
ThefollowingtableliststhepossibleTraceOutputOptionsvalues.
Value Description
Callstack Writethecallstack,whichisrepresentedbythereturnvalueoftheEnvironment.StackTraceproperty.
DateTime Writethedateandtime.
LogicalOperationStack Writethelogicaloperationstack,whichisrepresentedbythereturnvalueoftheCorrelationManager.LogicalOperationStackproperty.
ProcessId Writetheprocessidentity,whichisrepresentedbythereturnvalueoftheProcess.IDproperty.
ThreadId WritetheThreadIdentity,whichisrepresentedbythereturnvalueoftheThread.ManagedThreadIdPropertyforthecurrentthread.
Timestamp Writethetimestamp,whichisrepresentedbythereturnvalueoftheSystem.Diagnostics.Stopwatch.GetTimeStampmethod.
Formoreinformationaboutthesevalues,seeTraceOptionsFieldsinthe.NETFrameworkClassLibraryonMSDN®.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 741: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/741.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringWCFIntegrationTraceListeners
WindowsCommunicationFoundation(WCF)isabletologdirectlyonlytoSystem.Diagnosticstracesources,soitisnecessarytoconfigureaspecialtracelistenernamedtheEntLibLoggingProxyTraceListenerinthe<system.diagnostics>configurationsectiontoenabletheLoggingApplicationBlocktoprocessWCFlogmessages.Thistracelistenerreceivesmessagesfromthetracesource,wrapstheminaLogEntryobject,andforwardsthemtotheLoggingApplicationBlock,wheretheycanbeprocessedaccordingtotheLoggingApplicationBlock’sconfiguration.IftheoriginalmessageisinXMLformat(asisthecasewhenmessagesaregeneratedfromWCF),theEntLibLoggingProxyTraceListenercreatesanXmlLogEntryobjectinsteadofaLogEntry.TheXmlLogEntryclassisderivedfromthestandardLogEntryclassandaddssupportforanXMLpayload.
TheEntLibLoggingProxyTraceListenerwilladdthenameofitscontainingtracesourceasacategorytoeachXmlLogEntryitcreates.Inaddition,itispossibletoconfiguretheEntLibLoggingProxyTraceListenertoextractinformationfromtheXMLdataforuseasadditionalcategories.ThiscanbespecifiedusingXPathqueriesinthedefinitionofthetracelistenerintheconfigurationfile.ThecategoriesXPathQueriesattributecanbesettoasemicolon-delimitedlistofXPathqueries,andthenamespacesattributecanbesettoaspace-delimitedlistofXMLnamespacesusedintheXPathqueries,asshowninthefollowingexample.XML
<addname="entlibproxywithmultiplexpaths"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EntLibLoggingProxyTraceListener,
Microsoft.Practices.EnterpriseLibrary.Logging"
categoriesXPathQueries="//MessageLogTraceRecord/@Source;//MessageLogTraceRecord/@Source2"
namespaces="xmlns:pre='urn:test'xmlns:pre2='urn:test2'"/>
TousetheEntLibLoggingProxyTraceListenerwithWCF,youwillneedtodefineatracesourcenamedSystem.ServiceModelinthe<system.diagnostics>configurationsectionandturnonlogginginWCFby
![Page 742: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/742.jpg)
specifyingappropriatevaluesinthe<diagnostics>sectioninthe<system.serviceModel>configurationsection.NotethattheEnterpriseLibraryconfigurationtoolsdonotsupporteditingeitherofthesesections,soyoumustuseatexteditororalternativeeditor.Formoreinformation,seeSystem.ServiceModelNamespaceonMSDN.FormoreinformationaboutusingtracingwithWCF,seeConfiguringTracingonMSDN.
AlthoughyoucanuseanyofthetracelistenerssupportedbytheLoggingApplicationBlockwithWCF,themostcommonscenarioistologthemessagesinXMLformat.XMLfilesloggedfromWCFcanbeanalyzedintheServiceTraceViewerapplicationthatisincludedintheWindowsSDK.ToconfiguretheLoggingApplicationBlocktologmessagesinthisXMLformat,youshouldusetheXmlTraceListener.ThistracelistenerderivesfromtheXmlWriterTraceListener,whichisapartofthe.NETFramework,andisabletoextracttheXMLpayloadfromanXmlLogEntryobjectandwritethisdatatoanXMLtextfile.YoucananalyzetheoutputofthistracelistenerwiththeWCFlogfileanalysistools.
Asampleconfigurationfilethatdemonstrateswhattheconfigurationshouldlooklikefollowsthenextprocedure.The<system.serviceModel>sectionofthefiledefineshowtheWCFservicebehavesandisnotrelevanttotheactualloggingprocess.
ThefollowingproceduredescribeshowtointegratetheLoggingApplicationBlockwithapplicationsthatuseWCF.
ToconfiguretheWCF-integrationtracelisteners1. CreateoropenaconfigurationfileinoneoftheEnterpriseLibrary
configurationtools,andensuretheLoggingApplicationBlockisaddedtotheapplication’sconfiguration.Formoreinformation,seeConfiguringEnterpriseLibrary.
2. ClicktheplussigniconintheLoggingTargetListenerspane,pointtoAddLoggingTargetListener,andthenclickAddXMLTraceListener.
3. (Optional)Inthepropertiespane,settheName,theFileNameforthetracefile,theSeverityFilterforthelevelofmessagetodetect,andselectavaluefortheTraceOutputOptionspropertytospecifywhichoptionsorelementsshouldbeincludedinthetraceoutput.Formoreinformation,seeTraceOutputOptionsValues.
![Page 743: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/743.jpg)
4. ClicktheplussigniconintheCategoriespaneandclickAddCategory.
5. Inthepropertiespane,settheNametoSystem.ServiceModel;setAutoFlushandMinimumSeverityasrequired.
6. ClicktheListenerspropertyplussignicon,thenselecttheXMLTraceListenerfromthedrop-downlist.
7. Savetheconfigurationfile.8. OpentheconfigurationfileeitherinVisualStudio®orinthetexteditor
ofyourchoice.9. DefinetheEntLibProxytracelistenerinthe<system.diagnostics>
sectionanduseSystem.ServiceModelasthesource.(Seethesampleconfigurationfile.)
10. ModifytheWCFconfigurationtospecifythedesiredleveloflogging,asshowninthefollowingsampleconfigurationfile.
XML
<?xmlversion="1.0"encoding="utf-8"?>
<configuration>
<configSections>
<sectionname="loggingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary
.Logging.Configuration.LoggingSettings,
Microsoft.Practices.EnterpriseLibrary.Logging"/>
</configSections>
<loggingConfigurationname="LoggingApplicationBlock"
tracingEnabled="true"
defaultCategory="System.ServiceModel"
logWarningsWhenNoCategoriesMatch="true">
<listeners>
<addfileName="c:\\trace-xml.log"
listenerDataType="Microsoft.Practices.EnterpriseLibrary
.Logging.Configuration.XmlTraceListenerData,
Microsoft.Practices.EnterpriseLibrary.Logging"
traceOutputOptions="None"
type="Microsoft.Practices.EnterpriseLibrary.Logging
.TraceListeners.XmlTraceListener,
Microsoft.Practices.EnterpriseLibrary.Logging"
![Page 744: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/744.jpg)
name="XMLTraceListener"/>
</listeners>
<formatters>
</formatters>
<categorySources>
<addswitchValue="All"name="System.ServiceModel">
<listeners>
<addname="XMLTraceListener"/>
</listeners>
</add>
</categorySources>
<specialSources>
<allEventsswitchValue="All"name="AllEvents"/>
<notProcessedswitchValue="All"name="UnprocessedCategory"/>
<errorsswitchValue="All"name="LoggingErrors&Warnings"/>
</specialSources>
</loggingConfiguration>
<system.serviceModel>
<diagnostics>
<messageLogginglogEntireMessage="true"
logMalformedMessages="true"
logMessagesAtTransportLevel="true"/>
</diagnostics>
<services>
<servicename="WCFServiceLibrary1.service1"
behaviorConfiguration="MyServiceTypeBehaviors">
<endpointcontract="WCFServiceLibrary1.IService1"
binding="wsHttpBinding"/>
<endpointcontract="IMetadataExchange"binding="mexHttpBinding"
address="mex"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behaviorname="MyServiceTypeBehaviors">
<serviceMetadatahttpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
![Page 745: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/745.jpg)
</system.serviceModel>
<system.diagnostics>
<sources>
<sourcename="System.ServiceModel"switchValue="All">
<listeners>
<addname="traceListener"
type="Microsoft.Practices.EnterpriseLibrary.Logging
.TraceListeners.EntLibLoggingProxyTraceListener,
Microsoft.Practices.EnterpriseLibrary.Logging"/>
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>
ForinformationabouttheWCF-integrationtracelistenerproperties,seeTraceListenerProperties.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 746: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/746.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringFormatters
Thefirstproceduredescribeshowtoconfiguretheformatters.Thetextformatterconvertsalogentryintoatextstring.Thecontentsofthestringaredeterminedbyreplacingtokensinthetextformatter'sTemplateproperty.TheBinaryLogFormatterusesthe.NETFrameworkBinaryFormattertoserializeanddeserializethelogentryinbinaryformat.TheBinaryLogFormatterisrequiredwhenusingtheMessageQueuing(MSMQ)tracelistenerwiththeMessageQueuingdistributorservice.
Toconfigureformatters1. ClickontheplussigniconintheLogMessageFormatterssectionof
theLoggingSettingsconfigurationpaneandclickAddLogMessageFormatterstodisplaythelistofformatters.Whenyouselectaformatter,itisaddedtotheLogMessageFormatterssectionwhereyoucanthensetitsproperties.
2. Clicktheexpanderarrowintheformatteritemyouwishtoconfigureifthepropertiesarenotvisible.
3. (Optional)ChangetheNameproperty.Thedefaultnameisthenameoftheformatter.
4. Ifyouareaddingatextformatterandwanttochangethetemplatethatcontainsthevalueplaceholders,clicktheellipsisbutton(…)fortheTemplateproperty.MaketherequiredchangesintheTemplateEditordialog.YoucanusetheInsertTokenbuttontoaddtokenswiththeappropriatesyntax.Afteryoufinishmakingthechanges,clickOK.
5. IfyouareaddingaCustomFormatterandwanttoaddoreditthesettings,changethelistofkeysandvaluesintheAttributespropertysection.
6. Repeattheprocedureforeachformatteryouwanttouse.Note:
Theonlypropertyyoucanchangeforthebinaryformatteristhename.
![Page 747: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/747.jpg)
TextFormatterTemplateTokensToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 748: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/748.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringTraceSourceCategories
Tracesourcecategoriesassociatelogentrieswiththeirtargetlistener(s).Youcanconfigurethefollowingtwocategorytypes:
Categoriesthatspecifytheloggingcategoriesyouwanttouse.Whenyoucreatealogentry,youcanassignittooneormorecategories.Eachcategorycanfilterthelogentrybasedonitsseverity(suchasCritical,Error,Warning,orInformation),androuteittooneormoretracelisteners(loggingtargets).SpecialCategoriesthatautomaticallyreceivealllogentries,unprocessedlogentries,orlogentrieswhereanerroroccurredduringlogging.Eachofthesespecialcategoriescanfilterthelogentrybasedonitsseverity(suchasCritical,Error,Warning,orInformation),androuteittooneormoretracelisteners(loggingtargets).
![Page 749: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/749.jpg)
ConfiguringTraceSourceCategories
![Page 750: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/750.jpg)
ConfiguringTraceSourcesSpecialCategory
![Page 751: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/751.jpg)
SourceCategoryProperties
![Page 752: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/752.jpg)
Severity(SourceLevels)ValuesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 753: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/753.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringLoggingFilters
Youcanfilterlogentriesbasedontheircategoriesandtheirpriorities.Youcanalsoentirelyenableordisableloggingoraddacustomloggingfilter.Thefollowingproceduredescribeshowtoconfiguretheloggingfilters.
Toconfigureloggingfilters1. SelectAddLoggingFiltersasdescribedinConfigurationOverview.2. Ifthefilter'spropertypaneisnotdisplayed,clickthepropertyexpander
arroworright-clickthefiltersnodeyouwishtoconfigure.3. TheCategoryFilterallowsordenieslogentriesbasedontheir
categories:IfyouwanttouseaCategoryFilter,youcanselectthespecificcategoryfilterbyeditingtheCategoriesproperty.Clicktheplussignicontoaddacategoryfilter.Typeorselectthecategorynameforthecategorythatwillbefiltered.Youcaneitherselectanamefromthedrop-downlistortypeacategoryname.AllCategoryFiltersthathavebeenaddedtotheCategoryFilterssectionareavailableforselectioninthedrop-downlist.Theselectedcategorynameappearsinthelowerpane.Repeattoaddanyothercategoriesyourequire.Toremoveacategory,clickthedelete(x)iconbesidethecategoryyouwishtoremove.Repeattoremoveanyothercategoriesyounolongerrequire.Selectafiltermode,eitherAllowAllExceptDeniedorDenyAllExceptDenied.(Optional)Changethenameofthecategoryfilter.ForinformationabouttheCategoryFilterproperties,seeCategoryFilterProperties.
4. TheLoggingEnabledFilterprovidesaglobalswitchthatyoucanusetoturnloggingonandoff:
Ifyouwanttologevents,setAllLoggingEnabledtoTrue.Topreventalllogging,setAllLoggingEnabledtoFalse.(Optional)ChangethenameoftheLoggingEnabledFilter.
![Page 754: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/754.jpg)
ForinformationabouttheLoggingEnabledFilterproperties,seeLoggingEnabledFilterProperties.
5. ThePriorityFilterallowsordenieslogentriesbasedontheirpriority:(Optional)SettheMaximumPriorityproperty.Thisisthemaximumpriorityvaluealogentrycanhaveinordertobelogged.Ifyoudonotsetthisproperty,thevalueis2147483647(thisisthelargestpossiblevalueofa32-bitsignedinteger).(Optional)SettheMinimumPriorityproperty.Thisistheminimumvaluealogentrymusthavetobelogged.Ifyoudonotsetthisproperty,thevalueis-1.(Optional)Changethenameofthepriorityfilter.Forinformationaboutthepriorityfilterproperties,seePriorityFilterProperties.
6. ACustomLoggingFilterisaclassthatyouhavecreatedthatderivesfromtheLogFilterclass.Itsconfigurationinformationconsistsofacollectionofname/valuestringpairs:
SettheTypepropertybyclickingtheellipsisbutton(...)todisplaytheTypeSelector.NavigatetoandclickthefiltertypenameintheTypeSelectordialogbox.YoumustselectaclassthatderivesfromtheLogFilterclass.ItmustalsohavethetypeCustomLogFilterDataspecifiedasthevalueoftheConfigurationElementTypeattributeplacedontheclass.Enterakey/valuepairintheKeyandValuetextboxes.Whenyouenterakey/valuepair,anewpairofblanktextboxesaredisplayed.(Optional)ChangethenameoftheCustomLoggingFilter.ForinformationabouttheCustomLoggingFilterproperties,seeCustomLoggingFilterProperties.
7. Repeattheprecedingstepsforeachfilteryourequire.
![Page 755: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/755.jpg)
CategoryFilterProperties
![Page 756: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/756.jpg)
LoggingEnabledFilterProperties
![Page 757: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/757.jpg)
PriorityFilterProperties
![Page 758: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/758.jpg)
CustomLoggingFilterPropertiesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 759: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/759.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringtheApplicationBlock
ThefollowingproceduredescribeshowtoconfiguretheLoggingApplicationBlockproperties.
ToconfiguretheLoggingApplicationBlock1. IntheLoggingSettingssection,clickeachpropertyyouwantto
change.ForinformationabouttheLoggingApplicationBlockproperties,seethetablethatfollowsthisprocedure.
2. Setthepropertiesifyouneedto.Ifyouwanttouseadefaultcategory,clickthedrop-downarrowandselectoneofthecategorynames.Logentriesthatarenotassignedtoacategorybelongtothedefaultcategory.
3. TheWarnIfNoCategoryMatchpropertysendslogentriesthatareassignedtoacategorythatisnotspecifiedinconfigurationtotheLoggingErrors&Warningsspecialsource.ThedefaultisTrue.Ifyoudonotwantthistooccur,clickFalseinthedrop-downlist.
4. TheActivityTracingEnabledpropertyspecifieswhetheractivitytracingisenabled.ThedefaultisTrue.Ifyoudonotwantthistooccur,clickFalseinthedrop-downlist.
![Page 760: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/760.jpg)
LoggingApplicationBlockProperties
![Page 761: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/761.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 762: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/762.jpg)
MicrosoftEnterpriseLibrary5.0
SourceSchemafortheLoggingApplicationBlock
ThistopicliststheelementsandattributesusedtoconfiguretheLoggingApplicationBlock.Theconfigurationfilehasthefollowingsection-handlerdeclaration.XML
<configSections>
<sectionname="loggingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings,
Microsoft.Practices.EnterpriseLibrary.Logging"/>
</configSections>
Thesection-handlerdeclarationcontainsthenameoftheconfigurationsettingssectionandthenameofthesection-handlerclassthatprocessesconfigurationdatainthatsection.ThenameoftheconfigurationsettingssectionisloggingConfiguration.Thenameofthesection-handlerclassisMicrosoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings
![Page 763: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/763.jpg)
loggingConfigurationElement
![Page 764: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/764.jpg)
logFiltersChildElement
![Page 765: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/765.jpg)
categoryFiltersChildElement
![Page 766: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/766.jpg)
categorySourcesChildElement
![Page 767: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/767.jpg)
listenersChildElement(categorySources)
![Page 768: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/768.jpg)
specialSourcesChildElement
![Page 769: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/769.jpg)
listenersChildElement(errors)
![Page 770: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/770.jpg)
notProcessedChildElement
![Page 771: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/771.jpg)
listenersChildElement(notProcessed)
![Page 772: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/772.jpg)
allEventsChildElement
![Page 773: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/773.jpg)
listenersChildElement(allEvents)
![Page 774: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/774.jpg)
listenersChildElement(loggingConfiguration)
![Page 775: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/775.jpg)
formattersChildElement
![Page 776: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/776.jpg)
msmqDistributorSettingsElement
![Page 777: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/777.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 778: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/778.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheDistributorService
Applicationsmustoftensendlogentriesfrommultiplesourcestoacommondestination.TheLoggingApplicationBlocktakesadvantageofMessageQueuing(alsoknownasMSMQ)toallowyoutodothis.Byconfiguringmultipleapplicationstousethesamemessagequeue,youcanprocesslogentriesatacentrallocation.
Todistributelogentriestoacentraldestination,configureyourapplicationtowritelogentriestothemessagequeuingtracelistener.WhentheapplicationsendsalogentrytotheLoggingApplicationBlock,itplacesthelogentryonaMessageQueuingqueue.ThedistributorservicerunsasaWindowsserviceoneitherthesamecomputerastheapplicationoronaremotecomputer.Itpollsthequeuetoseeifthereareanylogentriesonit.Thepollingintervalisdeterminedbyconfiguration.
Iftherearelogentriesonthequeue,thedistributorserviceusesaninstanceoftheLoggingApplicationBlocktoforwardthemessagestothetracelistener(s).Thetracelistener(s)writethelogentriestothedestinations,suchasaneventlogoraflatfile.
ThedistributorservicerequiresthatalllogentriesbeformattedusingtheBinaryLogFormatterclass.Iftheservicecannotinterprettheentry,itwillloganerrortotheApplicationEventLogandshutdown.
Thefollowingschematicillustrateshowmultipleapplicationsusethedistributorservicetosendlogentriestoacentrallocation.
![Page 779: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/779.jpg)
EachinstanceoftheLoggingApplicationBlockusesaninstanceofthemessagequeuingtracelistener(theMsmqTraceListenerclass)tosendthelogentriestoasingledestinationqueue.ThedistributorservicepollsthequeueandusesanotherinstanceoftheLoggingApplicationBlocktodirectthelogentriestothepropertracelisteners.Notethatthedistributorservicecanrunonaremotecomputer.Thefollowingsectionsdescribeinstallingandusingthedistributorservice:
InstallingtheDistributorServiceStartingtheDistributorServiceUnderstandingtheserviceNameAttribute
![Page 780: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/780.jpg)
InstallingtheDistributorService
![Page 781: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/781.jpg)
StartingtheDistributorService
![Page 782: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/782.jpg)
UnderstandingtheserviceNameAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 783: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/783.jpg)
MicrosoftEnterpriseLibrary5.0
AddingApplicationCode
TheLoggingApplicationBlockisdesignedtosupportthemostcommonscenariosforlogginginformation.Whenaddingyourapplicationcode,refertothescenariosintheKeyScenariossectionsandselecttheonesthatbestsuityoursituation.Usethecodethataccompaniesthescenarioeitherasitisoradaptitasnecessary.
First,prepareyourapplicationtousetheLoggingApplicationBlock.ThefollowingproceduredescribeshowtoincludethenecessaryEnterpriseLibraryassembliesandelementsinyourcode.
Toprepareyourapplication1. SetareferencetotheLoggingApplicationBlockassembly:
IfyouareusingC#,inVisualStudio,right-clickReferencesinSolutionExplorer,andthenclickAddReferencestoaddreferencestothefollowingassemblies:
Microsoft.Practices.Unity.dllMicrosoft.Practices.Unity.Interception.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.EnterpriseLibrary.Logging.dll
IfyouareusingVisualBasic®,double-clickMyProjectinVisualStudio,clicktheReferencestab,andthenclickAddReferencetoselecttheassembly.Inthelistofimportednamespacesatthebottomofthetab,selectthefollowingcheckboxes:
Microsoft.Practices.Unity.dllMicrosoft.Practices.Unity.Interception.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.EnterpriseLibrary.Logging.dll
2. (Optional)TouseelementsfromtheLoggingApplicationBlockwithoutfullyqualifyingtheelementreference,youcanaddthefollowingusingstatements(C#)orImportsstatements(VisualBasic)tothetopofyoursourcecodefile.
![Page 784: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/784.jpg)
C#
usingMicrosoft.Practices.EnterpriseLibrary.Logging;
usingMicrosoft.Practices.EnterpriseLibrary.Logging.ExtraInformation;
usingMicrosoft.Practices.EnterpriseLibrary.Logging.Filters;
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Logging
ImportsMicrosoft.Practices.EnterpriseLibrary.Logging.ExtraInformation
ImportsMicrosoft.Practices.EnterpriseLibrary.Logging.Filters
Note:ForVisualBasicprojects,youcanalsousetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer,andthenclickPropertiesontheProjectmenu.WhentheProjectDesignerappears,clicktheReferencestab.
TheExtraInformationprovidersgathercontextinformationthatisusefulbutnotalwaysnecessarybecauseitisexpensivetocollect.ExamplesarestacktraceinformationandCOM+information.TheExtraInformationprovidersaddtheinformationtoadictionary.Youcanchoosewhichproviderstouse(ifany)andaddtheresultingdictionarytotheLogEntry.ExtendedPropertiesproperty.Filtersareoptional.YouonlyneedtoimporttheMicrosoft.Practices.EnterpriseLibrary.Logging.Filtersnamespaceifyouaregoingtorefertospecificfiltersinyourapplicationcode.
3. IfyouareusingtheDatabaseTraceListenerclass,youmustalsodothefollowing:
ConfiguretheapplicationtousetheDataAccessApplicationBlock.Formoreinformation,seeTheDataAccessApplicationBlock.ExecutethescriptnamedCreateLoggingDb.cmd(locatedintheSource\Blocks\Logging\Src\DatabaseTraceListener\Scriptsfolder)tocreatetheLoggingdatabase.
![Page 785: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/785.jpg)
Note:ItisalsoagoodideatoaddareferencetotheMicrosoft.Practices.EnterpriseLibrary.Logging.Database.dlltoyourprojectsothattheassemblyrequiredatruntimeiscopiedtotheoutputfolder.
4. Addtheapplicationcode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 786: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/786.jpg)
MicrosoftEnterpriseLibrary5.0
KeyScenarios
Thisseriesoftopicsdescribescommonsituationsdevelopersmustaddresswhenprovidingloggingfunctionalityintheirapplications.Eachscenarioexplainsthetask,describesareal-worldsituationwheresuchataskmightarise,andincludescodedemonstratinghowtousetheLoggingApplicationBlocktocompletethetask.Thescenariosareasfollows:
LoggingtoaDatabase.ThistopicdescribestheprocessyoushouldfollowforusingtheLoggingApplicationBlocktoimplementthecommonrequirementofloggingtoadatabase.LoggingtoWindowsEventLog.ThistopicdescribestheprocessyoushouldfollowforusingtheLoggingApplicationBlocktoimplementthecommonrequirementofloggingtoWindowsEventLog.LoggingtoaDiskFile.ThistopicdescribestheprocessyoushouldfollowforusingtheLoggingApplicationBlocktoimplementthecommonrequirementofloggingtoadiskfile.LoggingtoWindowsMessageQueuing.ThistopicdescribestheprocessyoushouldfollowforusingtheLoggingApplicationBlocktoimplementthecommonrequirementofloggingtoWindowsMessageQueuing.LoggingtoWMI.ThistopicdescribestheprocessyoushouldfollowforusingtheLoggingApplicationBlocktoimplementthecommonrequirementofloggingtotheWindowsManagementInstrumentationrepository.LoggingasE-mailMessages.ThistopicdescribestheprocessyoushouldfollowforusingtheLoggingApplicationBlocktoimplementthecommonrequirementofsendinglogginginformationine-mailmessages.PopulatingandRaisingEventsfromCode.Thisscenarioillustrateshowtowritecodetospecifythedatatobelogged,alongwithacategoryandpriority,andpassittotheapplicationblock.PopulatingaLogMessagewithAdditionalContextInformation.Thisscenarioillustrateshowtopopulateadictionaryofcustominformationtobeaddedtoalogentry.TracingActivitiesandPropagatingContextInformation.Thisscenarioillustrateshowtologthestartandendofanactivityandtracekeyactivitypointsinbetween.
![Page 787: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/787.jpg)
CheckingFilterStatusbeforeConstructingLogMessages.Thisscenarioillustrateshowtoavoidcollectingloginformationformessagesthatwillnotbeloggedaccordingtothecurrentconfigurationinformation.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 788: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/788.jpg)
MicrosoftEnterpriseLibrary5.0
LoggingtoaDatabase
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.Itdescribestheprocessforsettinguptheblocktosendlogeventstoadatabase.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasareferencetohelpyouquicklysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
![Page 789: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/789.jpg)
TypicalGoals
![Page 790: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/790.jpg)
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 791: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/791.jpg)
MicrosoftEnterpriseLibrary5.0
LoggingtoWindowsEventLog
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.ItdescribestheprocessforsettinguptheblocktosendlogeventstoWindowsEventLog.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasaquickreferencetohelpyourapidlysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
![Page 792: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/792.jpg)
TypicalGoals
![Page 793: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/793.jpg)
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 794: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/794.jpg)
MicrosoftEnterpriseLibrary5.0
LoggingtoaDiskFile
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.Itdescribestheprocessforsettinguptheblocktosendlogeventstoadiskfile.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasaquickreferencetohelpyouquicklysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
![Page 795: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/795.jpg)
TypicalGoals
![Page 796: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/796.jpg)
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 797: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/797.jpg)
MicrosoftEnterpriseLibrary5.0
LoggingtoWindowsMessageQueuing
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.ItdescribestheprocessforsettinguptheblocktosendlogeventsasmessagesthroughWindowsMessageQueuing.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasaquickreferencetohelpyouquicklysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
![Page 798: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/798.jpg)
TypicalGoals
![Page 799: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/799.jpg)
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 800: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/800.jpg)
MicrosoftEnterpriseLibrary5.0
LoggingtoWMI
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.ItdescribestheprocessforsettinguptheblocktosendlogeventstotheWindowsManagementInstrumentationdatabase.Theprocessjustinvolvesconfiguringtheblock—therearenoothertasksrequiredtoprepareyourapplication.ThistopicactsasaquickreferencetohelpyouquicklysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
![Page 801: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/801.jpg)
TypicalGoals
![Page 802: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/802.jpg)
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 803: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/803.jpg)
MicrosoftEnterpriseLibrary5.0
LoggingasE-mailMessages
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.Itdescribestheprocessforsettinguptheblocktosendlogeventsase-mailmessages.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasaquickreferencetohelpyourapidlysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
![Page 804: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/804.jpg)
TypicalGoals
![Page 805: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/805.jpg)
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 806: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/806.jpg)
MicrosoftEnterpriseLibrary5.0
PopulatingandRaisingEventsfromCode
TheabilitytopopulateandraiseeventsfromcodeisfundamentaltothefunctionalityoftheLoggingApplicationBlock.
![Page 807: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/807.jpg)
TypicalGoals
![Page 809: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/809.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 810: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/810.jpg)
MicrosoftEnterpriseLibrary5.0
PopulatingaLogMessagewithAdditionalContextInformation
TheLogEntryclassdefinespropertiestoholdinformationcommontotypicalloggingscenarios.Developersoftenneedtoaddcontextinformationtologentries.Thesametypeofcontextinformationcanberequiredformultiplelogentriesinthesameapplicationorinmultipleapplications.Becausecontextinformationcanbeexpensivetogather,certaintypesofinformationarenotautomaticallycollected.TheExtraInformationprovidersgathercontextinformationthatisusefulbutnotalwaysnecessarybecauseitisexpensivetocollect.ExamplesarestacktraceinformationandCOM+information.
![Page 811: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/811.jpg)
TypicalGoals
![Page 812: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/812.jpg)
Solution
![Page 813: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/813.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 814: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/814.jpg)
MicrosoftEnterpriseLibrary5.0
TracingActivitiesandPropagatingContextInformation
Insomecases,youwillneedtologinformationatthestartandendofaparticularactivity,includingtiminginformation.Inaddition,youcantracetheprogressoftheactivityatselectedpointsintheapplication.TracingallowsyoutoassociatealleventsbetweenthestartandendofanactivitywithanActivityIDpropertyandacategory.TheActivityIDpropertyallowsyoutocorrelatelogentriesthatarewrittenduringtheexecutionofanactivity.Youcanusefiltersandcategoriestodirectandcontroltheinformationproducedforaneventthatcanoccurinthecontextofanyactivity.
![Page 815: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/815.jpg)
TypicalGoals
![Page 817: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/817.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 818: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/818.jpg)
MicrosoftEnterpriseLibrary5.0
CheckingFilterStatusbeforeConstructingLogMessages
ByusingtheLoggingApplicationBlock,youcanquerythefilterstatustodeterminewhetheralogmessageshouldbeloggedaccordingtothefilterconfiguration.
![Page 819: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/819.jpg)
TypicalGoals
![Page 820: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/820.jpg)
Solution
![Page 821: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/821.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 822: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/822.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheLoggingApplicationBlock
TheLoggingApplicationBlockincludesthefollowingfeatures:AsimpleandconsistentwayofloggingeventinformationDistributionofinformationtomultiplesourcesActivitytracingtomarkthestartandendofanactivitysuchasausecaseSimplifiedapplicationblockconfigurationusingtheconfigurationtoolsExtensibilitythroughcustomtracelistenersandformatters
![Page 823: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/823.jpg)
DesignGoals
![Page 824: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/824.jpg)
DesignHighlights
![Page 825: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/825.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 826: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/826.jpg)
MicrosoftEnterpriseLibrary5.0
DesigningforSimpleandConsistentLoggingFunctionality
Developersfacemanyimplementationchoicesandrequirementswhentheyaddloggingfunctionalitytotheirapplications.Differentapplicationsmayloginformationtodifferentdestinations.Forexample,oneapplicationmayuseaneventlogandanotherapplicationmayuseaflatfile.Evenasingleapplicationmayloginformationtomultipledestinations.Asaresult,developersmustoftenwriteduplicatecodeforcommontaskssuchaswritingtoaneventlogortoaflatfile.
Uniformimplementationsmakethecodeeasiertounderstand,morepredictable,andeasiertomaintain.However,differentdevelopmentteamsroutinelyimplementdifferentloggingstrategies.TheLoggingApplicationBlockencapsulatesthelogicthatperformsloggingandtracingoperationsintoafewclassesthathavesmallnumbersofmethods.Thesemethodsarethesameforalllogmessagedestinations.ThismeansthatapplicationsthatusetheLoggingApplicationBlockareconsistentinthewaysthattheyloginformation.ByusingtheLoggingApplicationBlock,thisconsistencyremainsacrosssingleprojects,multipleprojects,orenterprise-scalesolutions.
![Page 827: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/827.jpg)
DesignImplications
![Page 828: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/828.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 829: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/829.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingtheLoggingApplicationBlock
Initsoriginalstate,theLoggingApplicationBlockworkswellfortypicalloggingscenarios.However,theremaybetimeswhenyouneedtocustomizesomeoftheapplicationblock'sbehaviortobettersuityourapplication'sparticularrequirements.Therearetwowaystodothis:youcanextendtheLoggingApplicationBlockusingthebuilt-inextensionpointsoryoucanmodifytheapplicationblockbymakingchangestoitssourcecode.Formoredetails,seethefollowingtopics:
ExtendingtheLoggingApplicationBlockExtendingandModifyingEnterpriseLibrary
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 830: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/830.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingtheLoggingApplicationBlock
TheLoggingApplicationBlockisdesignedtosuitavarietyofapplicationsandtoprovidethemostcommonlyusedloggingfunctions.Youcanextendtheapplicationblockthroughdesignatedextensionpoints.Typically,thesearecustomclasses,writtenbyyou,thatimplementaparticularinterfaceorderivefromanabstractclass.Becausethesecustomclassesexistinyourapplicationspace,youdonotneedtomodifyorrebuildtheapplicationblock.Instead,youdesignateyourextensionsusingconfigurationsettings.Additionally,withextensionpoints,youcanadapttheapplicationblocktosuittheneedsofanyparticularapplication.
Youcanextendthecapabilitiesoftheblockbyaddingcustomformatters,tracelisteners,andlogfilters.
CustomProviderorExtension InterfaceorBaseClass
LogEntryFormatter ILogFormatter
TraceListener CustomTraceListener
LogFilter ILogFilterLogFilter
FordetailedinformationabouthowtointegratecustomproviderswiththeEnterpriseLibraryconfigurationsystemandconfigurationtoolsseeCreatingCustomProvidersforEnterpriseLibrary.
ThefollowingproceduredescribesthegeneralapproachtoextendtheLoggingApplicationBlock.
ToextendtheLoggingApplicationBlock1. Createanewcustomclassandaddittoyourproject.2. Makesurethattheclassimplementstherequiredinterfaces,
constructors,andmethods.3. AddthecustomobjecttotheconfigurationoftheLoggingApplication
BlockusingtheEnterpriseLibraryconfigurationtools:Specifyyourcustomclassasthetypename.
![Page 831: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/831.jpg)
Specifyanycustomconfigurationpropertiesbymodifyingtheattributesoftheobject.
![Page 832: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/832.jpg)
CreatingaCustomLogEntryFormatter
![Page 833: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/833.jpg)
CreatingaCustomTraceListener
![Page 834: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/834.jpg)
CreatingaCustomLogFilterToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 835: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/835.jpg)
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetoseethattheinitialdeploymentoftheLoggingApplicationBlockisplannedandmanagedandthatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheapplicationblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheapplicationblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheapplicationblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedintheLoggingApplicationBlock,seethefollowingtopics:
LoggingApplicationBlockPerformanceCountersLoggingApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 836: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/836.jpg)
MicrosoftEnterpriseLibrary5.0
LoggingApplicationBlockPerformanceCounters
ThefollowingtabledescribestheLoggingApplicationBlockperformancecounters.
PerformanceCounterName
Description
Avg.TraceExecutionTime
Theaverageexecutiontimefortracedoperations.
LoggingEventsRaised/sec
Therateatwhichloggingeventswereraised.
TotalLoggingEventsRaised
Thetotalnumberofloggingeventsraised.
TotalTraceListenerEntriesWritten
Thetotalnumberofentriesthatweretracedbyindividualtracelisteners.
TotalTraceOperationsStarted
Thetotalnumberoftracingoperationsstarted.
TraceListenerEntriesWritten/sec
Therateatwhichlogentriesweretracedbyindividualtracelisteners.
TraceOperationsStarted/sec
Therateatwhichtracingoperationswerestarted.
Anaveragecountermeasuresavalueovertimeanddisplaystheaverageofthelasttwomeasurements.Aratecountersamplesanincreasingcountofeventsovertimeanddividesthevaluesbythechangeintimetodisplayarateofactivity.Formoreinformationaboutperformancecounters,seeOverviewofPerformanceMonitoringinthe.NETFrameworkClassLibraryonMSDN.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
![Page 837: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/837.jpg)
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 838: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/838.jpg)
MicrosoftEnterpriseLibrary5.0
LoggingApplicationBlockEventLogEntries
ThistopicliststheLoggingApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
![Page 839: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/839.jpg)
FailureLoggingErrorEvent
![Page 840: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/840.jpg)
LockAcquisitionErrorEvent
![Page 841: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/841.jpg)
ConfigurationFailureEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 842: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/842.jpg)
MicrosoftEnterpriseLibrary5.0
ThePolicyInjectionApplicationBlock
Policyinjectioncanbeusedtochangethebehaviorofyourcustomobjects,andalmostanyother.NETclass,inordertobettermanagecrosscuttingconcernsfortheseobjects.InthecurrentversionofMicrosoft®EnterpriseLibrary,policyinjectionisimplementedthroughtheUnityinterceptionmechanism.FormoreinformationseeInterceptionwithUnity.
WhilethePolicyInjectionApplicationBlockisstillincludedinthisreleaseofEnterpriseLibrary,itis(withtheexceptionofonecallhandler)asetoflegacycomponentssuchasthePolicyInjectionfacadethatsupportsbackwardscompatibilitywithapplicationsthatuseversionsofEnterpriseLibrarypriortoversion5.0.
Forinformationabouttheselegacycomponents,seetheguidanceforpreviousversionsofEnterpriseLibrary.ThisisavailableontheMicrosoftEnterpriseLibrarysiteonMSDN®,andincludesspecificinformationforCreatinganInstanceofanInterceptableTargetClass,detailsonusingthecreatemethod,detailsonusingthewrapmethod,andSpecifyingaConfigurationInstanceWhenCreatingandWrappingObjects.Youcan,inaddition,usetheconfigurationtoolsprovidedwiththisreleaseofEnterpriseLibrarytoconfigurepolicyinjectionifyoudecidetousethelegacyapproach.
Alsobeawarethat,evenifyoudecidetocontinuetousethebackwardscompatibilitytechniquesincludedinthePolicyInjectionApplicationBlock,youmuststillmakesomechangestoyourexistingapplication.Thelocationofallofthecallhandlers(withtheexceptionofthePerformanceCounterHandler)haschanged,soyoumustensurethatyoureferencetheappropriateassembliesandnamespacesinyourcode.
Thefivecallhandlersyoucanuse,andtheirassembliesandnamespacesare:Authorizationhandler
Classname:AuthorizationCallHandlerAssembly:Microsoft.Practices.EnterpriseLibrary.Security.dllNamespace:Microsoft.Practices.EnterpriseLibrary.Security.PolicyInjection
Exceptionhandlinghandler
![Page 843: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/843.jpg)
Classname:ExceptionCallHandlerAssembly:Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dllNamespace:Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.PolicyInjection
LogginghandlerClassname:LogCallHandlerAssembly:Microsoft.Practices.EnterpriseLibrary.Logging.dllNamespace:Microsoft.Practices.EnterpriseLibrary.Logging.PolicyInjection
ValidationhandlerClassname:ValidationCallHandlerAssembly:Microsoft.Practices.EnterpriseLibrary.Validation.dllNamespace:Microsoft.Practices.EnterpriseLibrary.Validation.PolicyInjection
PerformancecounterhandlerClassname:PerformanceCounterCallHandlerAssembly:Microsoft.Practices.EnterpriseLibrary.PolicyInjection.dllNamespace:Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers
TheCachinghandlerisnolongerincludedinEnterpriseLibraryduetoconcernsaroundtheissuesofcachecontaminationandotherlimitationspreviouslydocumented.IfyourequiretheCachinghandler,youcandownloadthepreviousversionfromtheEnterpriseLibrarycommunityWebsiteathttp://www.codeplex.com/entlib/andintegrateitwithEnterpriseLibrary.
MoreinformationaboutthechangestothePolicyInjectionApplicationBlockcanbefoundinthesectionChangesinThisReleaseintheintroductiontothisguidance.InformationaboutmigratingexistingapplicationstousethecurrentversionofEnterpriseLibrarycanbefoundintheMigrationGuideavailablefromtheEnterpriseLibrarycommunityWebsiteathttp://www.codeplex.com/entlib/.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,pleasesendemailto
![Page 844: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/844.jpg)
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 845: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/845.jpg)
MicrosoftEnterpriseLibrary5.0
TheSecurityApplicationBlock
DevelopersfrequentlywriteapplicationsthatmustauthorizeusersusingoneormoresecurityproviderssuchasMicrosoft®ActiveDirectory®directoryservice,AuthorizationManager,ActiveDirectoryLightweightDirectoryServices(ADLDS),andcustomauthorizationproviders.Theseapplicationsmayalsoneedtocacheauthenticationorauthorizationdataforthedurationofalogonsession.
TheSecurityApplicationBlocksimplifiesthesetasksbyhandlingtheminaconsistentmanner,abstractingtheapplicationcodefromthespecificsecurityproviders.Youcanevenchangeunderlyingprovidersthroughconfigurationwithoutchangingtheunderlyingapplicationcode.
TheSecurityApplicationBlockprovidescodethatwillhelpyouwiththefollowingscenarios:
AuthorizationCachingsecurity-relatedcredentials
ThissectionincludesthefollowingtopicsthatwillhelpyoutounderstandandusetheSecurityApplicationBlock:
WhatDoestheSecurityApplicationBlockDo?Thistopicprovidesabriefoverviewthatwillhelpyoutounderstandwhattheblockcando,andexplainssomeoftheconceptsandfeaturesitincorporates.Italsoprovidesasimpleexampleofthewaythatyoucanwritecodetousetheblock.WhenShouldIUsetheSecurityApplicationBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andanyalternativetechniquesyoumayconsider.Italsoprovidesdetailsofanylimitationsoftheblockthatmayaffectyourdecisiontouseit.DevelopingApplicationsUsingtheSecurityApplicationBlock.ThistopicexplainshowtoconfiguretheSecurityApplicationBlocktoperformcommontasksandhowtousetheblockinyourapplications.KeyScenarios.ThistopicdemonstrateshowtousetheSecurityApplicationBlocktoperformthemosttypicalsecurityoperations.DesignoftheSecurityApplicationBlock.Thistopicexplainsthe
![Page 846: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/846.jpg)
decisionsthatwentintodesigningtheSecurityApplicationBlockandtherationalebehindthosedecisions.ExtendingandModifyingtheSecurityApplicationBlock.Thistopicexplainshowtoextendtheblockbycreatingyourownprovidersandhowtomodifythesourcecode.DeploymentandOperations.ThistopicexplainshowtodeployandupdatetheSecurityApplicationBlock'sassembliesandalsocontainsinformationaboutconfiguration.
![Page 847: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/847.jpg)
MoreInformationFormoreinformation,seethefollowingpatterns&practicesguides:
ApplicationArchitecturefor.NET:DesigningApplicationsandServices.NETDataAccessArchitectureGuideDesignGuidelinesforExceptions
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 848: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/848.jpg)
MicrosoftEnterpriseLibrary5.0
WhatDoestheSecurityApplicationBlockDo?
TheSecurityApplicationBlockallowsyoutoperformtwoseparatebutrelatedtasks.Youcanauthorizeusersagainstarangeofauthorizationproviders,and/orcacheauser'sidentityandsecuritycontextforusethroughoutyourapplication.Thecoderequiredtousethesefeaturesissimple,andtheactualmechanicsofaccessingauthorizationsystemsandcachingidentitiesandsecuritycontextsareabstractedwithintheblock.Often,youonlyneedtowriteonelineofcodetoperformcommontasks.ThefollowingschematicshowsthebasicelementsoftheSecurityApplicationBlock.
TheSecurityApplicationBlockexposestwointerfacesthatyoucanaccessinyourcode:
AnAuthorizationProviderinterface,whichexposesthesinglemethodnamedAuthorizethattakesaninstanceofanIPrincipalobjectcontainingdetailsoftheuser'sidentityandroles.Dependingonthewaythatyouconfiguretheblock,theauthorizationcantakeplaceeitherthroughWindows®AuthorizationManager(AzMan)againstActive
![Page 849: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/849.jpg)
Directory,anXMLfile,oradatabase;orbyusingcustomrulesthatyoudefineandarestoredasXMLintheapplicationconfigurationfile.ASecurityCacheProviderinterface,whichexposesmethodsthatallowyoutosaveandretrieveauser'sidentityorsecuritycontextasanIIdentityinstance,IPrincipalinstance,orASP.NETProfileinstance.Eachcachedidentityorsecuritycontextisidentifiedbyatoken(bydefaultaGUID,thoughyoucancreateanduseyourownimplementationoftheITokeninterface).TheblockstoresthisinformationineitheradatabaseorinIsolatedStorageusingtheCachingApplicationBlock.YoucanalternativelycreateacustomproviderfortheCachingApplicationBlockanduseittocachetheinformationinthelocationandusingthetechniquesyouimplementinyourprovider.
Yourapplicationcanusetheseinterfacestoquicklyandeasilycacheuseridentitiesandsecuritycontexts,obtaintokensthatrepresentusers,expiretheseusers,andcheckifusersareauthorizedtoperformspecifictasksoroperations.However,togetthemostfromtheblock,youmustunderstandthedifferencesbetweentheWindowsIIdentityandIPrincipalinterfacesandcommonlyusedconcreteimplementationsofthesetypes.
AnidentityisrepresentedbyaconcreteimplementationoftheIIdentityinterface,usuallyaWindowsIdentity,GenericIdentity,PassportIdentity,orFormsIdentitydependingontheauthenticationtechniqueused.TheIPrincipalinterfaceprovidesthelinkbetweenanidentityandtherolesforthatidentity.InASP.NET,thecurrentIPrincipalinstanceforauserisavailablefromtheHttpContext.Userproperty.ThemethodsthatcacheandretrieveuseridentityandsecuritycontextacceptaninstanceofaclassthatimplementseithertheIIdentityorIPrincipalinterface,oranASP.NETProfileinstance.FormoreinformationaboutWindowsidentitiesandsecuritycontexts,seePrincipalandIdentityObjectsandRole-BasedSecurityonMSDN®.
![Page 850: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/850.jpg)
TypicalUsageoftheSecurityApplicationBlock
![Page 851: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/851.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 852: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/852.jpg)
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheSecurityApplicationBlock?
TheSecurityApplicationBlockincludesimplementationsoffunctionalitythatmakesiteasytoperformauthorization,security-relatedcaching,andsessionmanagement.Ifyourapplicationsrequiretheprovidedimplementations,youcanusetheSecurityApplicationBlocktoprovidethisfunctionality.However,theblockisalsodesignedtobeextensibleandincludesgenericprovidersforeachfunction.Youcanadapttheproviderstomeetyourownsecurityrequirements.
![Page 853: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/853.jpg)
ScenariosfortheSecurityApplicationBlock
![Page 854: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/854.jpg)
BenefitsoftheSecurityApplicationBlock
![Page 855: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/855.jpg)
LimitationsoftheSecurityApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 856: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/856.jpg)
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheSecurityApplicationBlock
ThistopicdescribeshowyoucanusetheSecurityApplicationBlocktodevelopapplications.Itexplainshowtoconfiguretheblockandincorporateitintoyourapplications,andhowtousetheblockforspecificscenariossuchasauthorizingauserforaparticulartask.ThistopicassumesthatyouareusingtheSecurityApplicationBlockinitsoriginalstate,withoutextendingit.(Tolearnhowtoaddfunctionality,seeExtendingtheSecurityApplicationBlock.)Thissectionincludesthefollowingtopics:
EnteringConfigurationInformationAddingApplicationCode
Allapplicationblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompile.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 857: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/857.jpg)
MicrosoftEnterpriseLibrary5.0
EnteringConfigurationInformation
TheseproceduresexplainhowtoconfiguretheSecurityApplicationBlock.FordetailsoftheschemafortheSecurityApplicationBlockconfiguration,seeSourceSchemafortheSecurityApplicationBlock.Youcanalsoconfiguretheblockincodebyusinganalternateconfigurationsource.Formoreinformation,seeAdvancedConfigurationScenariosandUsingtheFluentConfigurationAPI.
ToaddtheSecurityApplicationBlock1. Opentheconfigurationfile.Formoreinformation,seeConfiguring
EnterpriseLibrary.2. ClickAddSecuritySettingsontheBlocksmenu.3. TheconfigurationtoolautomaticallyaddstheSecuritySettingssection
withdefaultsettings.ClickthechevronarrowattherightofthesectionheadingtoviewSecuritySettingsproperties.
4. ClicktheAuthorizationProvidersplussignicon,pointtoAddAuthorizationProviders,thenclickthetypeofauthorizationruleprovideryourequireandconfiguretheproviderasshowninthefollowingprocedures.Note:
TheWindowsAuthenticationManager(AzMan)providerisavailableonlyifyouhaveinstalledtherequiredprerequisites,includingtheassemblyMicrosoft.Interop.Security.AzRoles.dll,andcompiledtheSecurityApplicationBlocktoincludethisprovider.Formoreinformation,seeAbouttheAzManProviderlaterinthistopic.
5. (Optional)ClicktheSecurityCachesplussignicon,pointtoAddSecurityCaches,thenclickthetypeofsecuritycacheprovideryourequireandconfiguretheproviderasshowninthefollowingprocedures.
6. (Optional)InthepropertiespaneoftheSecuritySettingssection,settheProtectionProviderproperty.Thetextboxdrop-downprovidesthreechoices(noprotection),RsaProtectedConfigurationProvider,andDataProtectionConfigurationProvider.Thedefaultisnoprotection.SeeEncryptingConfigurationDataforinformationabout
![Page 858: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/858.jpg)
therestrictionsonusingtheRsaProtectedConfigurationProvider.7. (Optional)Inthepropertiespane,settheRequirePermissionproperty
toTrueorFalse.ThedefaultisTrue.8. (Optional)Inthepropertiespane,settheDefaultAuthorization
Providerproperty.Thisistheauthorizationproviderinstancetouseifoneisnotspecifiedinthecode.Thedefaultisnone.
9. (Optional)Inthepropertiespane,settheDefaultSecurityCacheProviderproperty.Thisisthesecuritycacheproviderinstancetouseifoneisnotspecifiedinthecode.Thedefaultisnone.
AfteryouaddtheSecurityApplicationBlocktotheapplicationconfiguration,youneedtoconfiguresomeorallofthefollowingelements:
AuthorizationRuleProviderAzManProviderCustomAuthorizationProviderSecurityCacheCustomSecurityCacheProvider
![Page 859: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/859.jpg)
AuthorizationRuleProvider
![Page 860: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/860.jpg)
AzManProvider
![Page 861: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/861.jpg)
CustomAuthorizationProvider
![Page 862: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/862.jpg)
SecurityCache
![Page 863: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/863.jpg)
CustomSecurityCacheProviderToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 864: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/864.jpg)
MicrosoftEnterpriseLibrary5.0
SourceSchemafortheSecurityApplicationBlock
ThistopicliststheXMLelementsandattributesusedtoconfiguretheSecurityApplicationBlock.YoucanmanuallyedittheXMLdata,buttheEnterpriseLibraryconfigurationtoolsgreatlysimplifythistask.IfyouchoosetomanuallyedittheXML,usetheschemainformationcontainedinthistopic.
Theconfigurationfilehasthefollowingsection-handlerdeclaration.XML
<configSections>
<sectionname="securityConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Security.Configuration.SecuritySettings,
Microsoft.Practices.EnterpriseLibrary.Security"/>
</configSections>
Thesection-handlerdeclarationcontainsthenameoftheconfigurationsettingssectionandthenameofthesection-handlerclassthatprocessesconfigurationdatainthatsection.ThenameoftheconfigurationsettingssectionissecurityConfiguration.Thenameofthesection-handlerclassisMicrosoft.Practices.EnterpriseLibrary.Security.Configuration.SecuritySettings
![Page 865: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/865.jpg)
securityConfigurationElement
![Page 866: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/866.jpg)
authorizationProvidersChildElement
![Page 867: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/867.jpg)
rulesChildElement
![Page 868: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/868.jpg)
securityCacheProvidersChildelement
![Page 869: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/869.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 870: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/870.jpg)
CopyCode
MicrosoftEnterpriseLibrary5.0
AddingApplicationCode
TheSecurityApplicationBlockisdesignedtosupportthemostcommonscenariosforauthorizationandcachingofsecurityinformation.Whenyouaddyourapplicationcode,refertothescenariosintheKeyScenariossection,andselecttheonesthatbestmatchyoursituation.Usethecodethataccompaniesthescenarioas-isoradaptitasnecessary.
First,youmustprepareyourapplicationtousetheSecurityApplicationBlock.
Toprepareyourapplication1. AddareferencetotheSecurityApplicationBlockassembly.InVisual
Studio,right-clickyourprojectnodeinSolutionExplorer,andthenclickAddReferences.ClicktheBrowsetab,andthennavigatetothelocationoftheMicrosoft.Practices.EnterpriseLibrary.Security.dllassembly.Selecttheassembly,andthenclickOKtoaddthereference.
2. Followthesameproceduretosetareferencetothefollowingassemblies:
Microsoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.Unity.dllMicrosoft.Practices.Unity.Interception.dll
3. Ifyouintendtousesecuritycaching,setareferencetotheassemblyMicrosoft.Practices.EnterpriseLibrary.Security.Cache.CachingStore.dllYoualsoneedtoaddareferencetotheDataAccessApplicationBlockassembly,Microsoft.Practices.EnterpriseLibrary.Data.dll,ifyouareusingtheDatabaseCacheStoragestoreintheCachingApplicationBlock.
4. (Optional)TouseelementsfromtheSecurityApplicationBlockwithoutfullyqualifyingtheelementreference,youcanaddtheusingstatement(C#)orImportsstatement(VisualBasic)tothetopofyoursourcecodefile.ThefollowingcodeshowshowtoaddthesestatementsfortheMicrosoft.Practices.EnterpriseLibrary.Securitynamespace.C#
![Page 871: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/871.jpg)
usingMicrosoft.Practices.EnterpriseLibrary.Security;
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Security
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 872: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/872.jpg)
MicrosoftEnterpriseLibrary5.0
KeyScenarios
Thistopicdescribesthemostcommonsituationsdevelopersmustaddresswhenprovidingsecurityfunctionalityintheirapplications.Eachscenarioexplainsthetask,describesareal-worldsituationwheresuchataskmightoccur,andincludescodethatdemonstrateshowtousetheSecurityApplicationBlocktocompletethetask.Thescenariosarethefollowing:
ObtainingaTemporaryTokenforanAuthenticatedUser.ThisscenarioillustrateshowtousetheSaveIdentitymethodtocacheanauthenticatedidentityandreturnatemporarytokenthatservesasanalternativetousercredentialsforthedurationoftheusersession.Youcanalsousethistechniquetosaveauserprincipalorauseridentity.AuthenticatingaUserUsingaToken.ThisscenarioillustrateshowtousetheGetIdentitymethodtoreturnanidentitythathasalreadybeencached,whenprovidedwithavalidtoken.Thesametechniquecanbeusedtoretrieveauserprincipaloruserprofile.TerminatingaUserSession(ExpiringaToken).ThisscenarioillustrateshowtousetheExpireIdentitymethodtoexpireatokencorrespondingtoanidentity,whentheusersessionends.Youcanalsousethistechniquetoexpireauserprincipalorauserprofile.DeterminingWhetheraUserIsAuthorizedtoPerformaTask.ThisscenarioillustrateshowtousetheAuthorizemethodofanauthorizationprovidertoperformauthorization.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 873: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/873.jpg)
MicrosoftEnterpriseLibrary5.0
ObtainingaTemporaryTokenforanAuthenticatedUser
Anexampleofwhenyoumightwanttoobtainatemporarytokenforanauthenticateduseriswhenyouwanttoimprovetheperformanceofyourapplicationbypassingthetokeninsteadoffrequentlyauthenticatingthesameuserduringasinglesession.Youcanusetheapproachdescribedheretosaveauserprincipalorauseridentityinthesecuritycacheandobtainatokenthatrepresentstheuser'sauthenticatedidentity.
![Page 874: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/874.jpg)
TypicalGoals
![Page 875: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/875.jpg)
Solution
![Page 876: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/876.jpg)
UsingSaveIdentity
![Page 877: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/877.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 878: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/878.jpg)
MicrosoftEnterpriseLibrary5.0
AuthenticatingaUserUsingaToken
Anexampleofwhenyoumightwanttouseatemporarytokenforauthenticationiswhenyouwanttoimprovetheperformanceofyourapplicationbypassingthetokeninsteadoffrequentlyauthenticatingauserduringasinglesession.Youcanusetheapproachdescribedheretoretrieveasaveduserprincipalorauseridentityfromthesecuritycacheusingatokenyoupreviouslyobtainedthatrepresentstheuser'sauthenticatedidentity.
![Page 879: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/879.jpg)
TypicalGoals
![Page 880: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/880.jpg)
Solution
![Page 881: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/881.jpg)
UsingGetIdentity
![Page 882: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/882.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 883: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/883.jpg)
MicrosoftEnterpriseLibrary5.0
TerminatingaUserSession(ExpiringaToken)
Anexampleofwhenyoumaywanttoexpireatokeniswhenyouwanttomakesurethatthetokencannotbeusedbyanattackeraftertheuserlogsout.Youcanusetheapproachdescribedheretoexpireauserprincipalorauseridentity.
![Page 884: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/884.jpg)
TypicalGoals
![Page 885: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/885.jpg)
Solution
![Page 886: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/886.jpg)
UsingExpireIdentity
![Page 887: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/887.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 888: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/888.jpg)
MicrosoftEnterpriseLibrary5.0
DeterminingWhetheraUserIsAuthorizedtoPerformaTask
Acommonsecurityrequirementistheneedtoauthorizeuserstoperformtasks.TheSecurityApplicationBlockhelpsbystandardizingaccesstoauthorizationproviderssuchastheAzManAuthorizationProviderortheAuthorizationRuleProvider,ortoauthorizationrulesstoredwithintheapplicationconfiguration.
![Page 889: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/889.jpg)
TypicalGoals
![Page 890: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/890.jpg)
Solution
![Page 891: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/891.jpg)
UsingAuthorize
![Page 892: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/892.jpg)
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 893: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/893.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheSecurityApplicationBlock
TheSecurityApplicationBlockaddressesthefollowingareas:AuthorizationSecurity-relatedcaching
![Page 895: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/895.jpg)
DesignHighlightsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 896: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/896.jpg)
MicrosoftEnterpriseLibrary5.0
DesigningforSimplifiedAuthorization
Uniformimplementationsmakecodeeasiertounderstand,morepredictable,andeasiertomaintain.However,developerscanimplementauthorizationinapplicationsinmanydifferentways.Forexample,theymayhavetouseanapproachthatconformstothesecuritypoliciesoftheirorganizations.Alternatively,theymayuseapproachesthatsuittheneedsofparticulardepartmentsoroftheapplicationsthemselves.
TheSecurityApplicationBlockencapsulatesthelogicthatperformsauthorizationoperationsintoasingleinterfacethatspecifiesonlyasmallnumberofmethods.Thesemethodscanbeusedbydifferentauthorizationproviders.ThismeansthatapplicationsthatusetheSecurityApplicationBlockareconsistentinthewaysthattheyauthorizeuserstoperformtasks.ByusingtheSecurityApplicationBlock,thisconsistencyremainsacrosssingleprojects,multipleprojects,orenterprise-scalesolutions.
![Page 897: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/897.jpg)
DesignImplications
![Page 898: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/898.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 899: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/899.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingtheSecurityApplicationBlock
Initsoriginalstate,theSecurityApplicationBlockworkswellfortypicalsecurityscenarios.However,theremaybetimeswhenyouhavetocustomizesomeoftheblock'sbehaviortobettersuityourapplication'sparticularrequirements.Therearetwowaystodothis.YoucanextendtheCachingApplicationBlockusingthebuilt-inextensionpoints.Youcanalsomodifytheblockbymakingchangestoitssourcecode.Formoredetails,seethefollowingtopics:
ExtendingtheSecurityApplicationBlockExtendingandModifyingEnterpriseLibrary
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 900: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/900.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingtheSecurityApplicationBlock
YouextendtheSecurityApplicationBlockthroughdesignatedextensionpoints.Typically,thesearecustomclasses,writtenbyyou,thatimplementaparticularinterfaceorderivefromanabstractclass.Becausethesecustomclassesexistinyourapplicationspace,youdonothavetomodifyorrebuildtheblock.Instead,youdesignateyourextensionsusingconfigurationsettings.
YoucanextendtheblockbyaddinganewtypeofAuthorizationProviderorbyaddinganewsecuritycacheproviderthatintegrateswithyourchosencachingmechanism.Thefollowingtableliststheinterfacesandbaseclassesthatyoucanusetoextendtheblock.
CustomProviderorExtension InterfaceorBaseClass
AuthorizationProvider AuthorizationProvider
SecurityCacheProvider ISecurityCacheProvider
FordetailedinformationabouthowtointegratecustomproviderswiththeEnterpriseLibraryconfigurationsystemandconfigurationtoolsseeCreatingCustomProvidersforEnterpriseLibrary.
![Page 901: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/901.jpg)
CreatinganAuthorizationProviderToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 902: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/902.jpg)
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetomakesurethattheinitialdeploymentoftheSecurityApplicationBlockisplannedandmanaged,andthatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheapplicationblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheSecurityApplicationBlock,seethefollowingtopics:
SecurityApplicationBlockPerformanceCountersSecurityApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 903: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/903.jpg)
MicrosoftEnterpriseLibrary5.0
SecurityApplicationBlockPerformanceCounters
ThefollowingtabledescribestheSecurityApplicationBlockperformancecounters.
Performancecountername Description
AuthorizationRequestsDenied/sec
Therateatwhichauthorizationrequestsweredenied.
AuthorizationRequests/sec Therateatwhichauthorizationrequestswerereceived.
SecurityCacheReads/sec Therateatwhichsecuritycachereadswererequested.
TotalAuthorizationRequests Thetotalnumberofauthorizationrequestsreceived.
TotalAuthorizationRequestsDenied
Thetotalnumberofauthorizationrequestsdenied.
TotalSecurityCacheReads Thetotalnumberofsecuritycachereadsrequested.
Aratecountersamplesanincreasingcountofeventsovertimeanddividesthevaluesbythechangeintimetodisplayarateofactivity.Formoreinformationaboutperformancecounters,seeOverviewofPerformanceMonitoringinthe.NETFrameworkClassLibraryonMSDN.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 904: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/904.jpg)
MicrosoftEnterpriseLibrary5.0
SecurityApplicationBlockEventLogEntries
ThistopicliststheSecurityApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
![Page 905: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/905.jpg)
ConfigurationFailureEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 906: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/906.jpg)
MicrosoftEnterpriseLibrary5.0
TheValidationApplicationBlock
Anyapplicationthatacceptsinputeitherfromusersorfromothersystemsmustensurethattheinformationisvalidintermsofsomesetofrulesthatyouspecify.Forexample,whenprocessinganorder,youmayneedtocheckthatacustomer'sphonenumberhasthecorrectnumberofdigitsorthatadatefallswithinaparticularrange.Inaddition,ifthevalidationfails,youmayneedtosendanerrormessagethatexplainswhatiswrong.
TheEnterpriseLibraryValidationApplicationBlockprovidesusefulfeaturesthatallowdeveloperstoimplementstructuredandeasy-to-maintainvalidationscenariosintheirapplications.Inaddition,theValidationApplicationBlockincludesadaptersthatallowyoutousetheapplicationblockwiththefollowingtechnologies:
ASP.NETWindows®CommunicationFoundation(WCF)WindowsPresentationFoundation(WPF)WindowsForms
ThissectionincludesthefollowingtopicsthatwillhelpyoutounderstandandusetheValidationApplicationBlock:
WhatDoestheValidationApplicationBlockDo?Thistopicprovidesabriefoverviewthatwillhelpyoutounderstandwhattheblockcando,andexplainssomeoftheconceptsandfeaturesitincorporates.Italsoprovidesasimpleexampleofhowyoucanwritecodetousetheblock.WhenShouldIUsetheValidationApplicationBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andalternativetechniquesyoumayconsider.DevelopingApplicationsUsingtheValidationApplicationBlock.ThistopicexplainshowtoincludetheValidationApplicationBlockinyourapplicationsandhowtoconfigureit.Italsocontainsmoredetailedinformation,suchashowtocreatecustommessagetemplatesandinformationonhowvalidationworkswithinheritance.KeyScenarios.ThistopicshowsdifferentwaystousetheValidationApplicationBlockinyourownapplications.
![Page 907: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/907.jpg)
DesignoftheValidationApplicationBlock.ThistopicincludesaclassdiagramoftheValidationApplicationBlock.ExtendingandModifyingtheValidationApplicationBlock.Thistopicexplainshowtoextendtheapplicationblockbyaddingcustomvalidatorsandattributes.Italsocontainsadviceabouthowtomodifythesourcecode.DeploymentandOperations.Thistopicexplainshowtodeployandupdatetheapplicationblockassemblies.Italsoexplainstheapplicationblock'sinstrumentation.
![Page 908: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/908.jpg)
MoreInformationForrelatedinformation,seethefollowingpatterns&practicesguides:
HowTo:ProtectFromInjectionAttacksinASP.NETSecurityPractices:ASP.NETSecurityPracticesataGlanceMicrosoftApplicationArchitectureGuide,2ndEdition
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 909: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/909.jpg)
MicrosoftEnterpriseLibrary5.0
WhatDoestheValidationApplicationBlockDo?
Unlikemanyothervalidationmechanismsandlibraries,whichuseseparatevalidationcontrolstovalidateindividualUIelementssuchastextboxes,theValidationApplicationBlockisdesignedtoallowyoutoeasilyvalidateinstancesofobjects.Thismeansthatyoucanexecutevalidationatanypointinyourapplication,andrepeatitwhenrequired.Forexample,youcanvalidateaninstanceofaclasspopulatedwithvaluesfromtheUI,validateaninstanceoftheclasspopulatedwithvaluesreceivedfromaWebservice,andvalidateaninstanceoftheclassasitpassesbetweenlayersofyourapplication.
Theblockprovidesalibraryofclassesnamedvalidators,whichimplementfunctionalityforvalidating.NETFrameworkdatatypes.Youcanalsogroupvalidatorstogetherinaruleset.Arulesetallowsyoutovalidateacomplexobjectorgraphbycomposingdifferentvalidatorsofdifferenttypesandapplyingthemtoelementsintheobjectgraph.Examplesoftheseelementsincludefields,properties,andnestedobjects.
Youconfigurevalidationrequirementsforspecificclassesbydefiningthesetofvalidatorsandtherulestoapplywhenvalidatingparameterandpropertyvaluesforinstancesofthatclass.Then,inmanysituations,youcanvalidateaninstanceoftheclasswithasinglelineofcode.
Youcandefinevalidationrulesandcarryoutvalidationinthefollowingways:Byusingconfigurationtodefinerulesetsforspecificclasses.Theserulessetsarestoredinyourapplicationconfigurationfile,andcanbecreatedusingthegraphicalconfigurationtools.Byaddingattributestomembersofyourclassestodefineindividualrulesforpublic,readableparametersandpropertiesthatspecifyrulesetsorindividualvalidationrules.ThesemaybeattributesdefinedwithintheValidationApplicationBlockthatdirectlytargetthevalidatorsprovidedwiththeblock,or.NETDataAnnotationattributes.TheValidationApplicationBlockworkswithbothofthesetypesofattributes.Byaddingcodetoyourclassesthatperformselfvalidationoftheobjectparametersorproperties.Thisisausefulwaytoimplementverycomplexvalidationrulesthatdependontheenvironmentorexternalfactors.
![Page 910: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/910.jpg)
Byusingcodetocreateinstancesofvalidatorsandthenexecutevalidationondemand.
Note:TheValidationApplicationBlockonlyappliesrulesspecifiedforthereturnvaluesforpublicmethodsthathavenoparameters.Tovalidateparameterswhenamethodisinvoked,ortovalidatereturnvaluesformethodsthatacceptparameters,youcanuseTheValidationHandler.Thishandlervalidatesparametervaluesbasedontherulesforeachparameter'stypeandanyvalidationattributesontheparametersthemselves.
TheValidationApplicationBlockcontainsawidevarietyofvalidators,andyoucaneasilycreatecustomvalidatorsyourselfforyourownspecificscenarios.Asexamplesofthevalidators,theblockincludesavalidatorthatchecksfornullstringsandanothervalidatorthatcheckswhetheranumberfallswithinaspecifiedrange.TherearealsospecialvalidatorsnamedtheAndCompositeValidatorandtheOrCompositeValidator.IfyoucreateanAndCompositeValidator,whichaggregatesothervalidators,allvalidatorsinthecompositevalidatormustreturntrueforsuccessfulvalidation.IfyoucreateanOrCompositeValidator,atleastoneofthevalidatorsinthecompositevalidatormustreturntrueforsuccessfulvalidation.
TheValidationApplicationBlockalsoincludesadaptorsthatyoucanuseinyourapplicationUIthatsupportthesametypeofimplementationasASP.NET,WindowsPresentationFoundation(WPF),andWindowsFormsvalidationcontrolstoprovidefeedbackandinformationtouserswhenvalidationerrorsoccur.Inaddition,theblockincludesanadapterthatmakesiteasytouseinWCFapplications.
![Page 911: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/911.jpg)
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 912: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/912.jpg)
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheValidationApplicationBlock?
YoushouldconsiderusingtheValidationApplicationBlockifyouwanttoencapsulatevalidationgoodpracticeintoeasilymaintainablecodethatyoucanreuse.Encapsulationalsoallowsyoutoseparatetheapplicationcodefromthevalidationlogic.Insomesituations,youmaybeabletoupdatethevalidationlogicwithoutredeployingtheapplication.
Inaddition,considerusingtheblockwhenyourvalidationcodemustworkacrossmultiplelayersoftheapplication'sarchitecture.Bydefiningrulesintheconfigurationforeachsegment,youcanreusethesamerulesetsinmultiplelocationswithinyourcode.
![Page 913: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/913.jpg)
ScenariosfortheValidationApplicationBlock
![Page 914: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/914.jpg)
BenefitsoftheValidationApplicationBlock
![Page 915: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/915.jpg)
AlternativestotheValidationApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 916: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/916.jpg)
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheValidationApplicationBlock
ThissectiondescribeshowtousetheValidationApplicationBlockinyourapplications.Itexplainshowtoconfiguretheapplicationblock,andhowtoincorporatetheapplicationblockintoyourapplication.Thissectionincludesthefollowingtopics:
EnteringConfigurationInformationAddingApplicationCodeUsingtheValidationBlockValidatorsUnderstandingCommonValidatorPropertiesUnderstandingValidationResultsHowValidatorsAreCreatedValidationandInheritance
Allapplicationblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompileit.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 917: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/917.jpg)
MicrosoftEnterpriseLibrary5.0
EnteringConfigurationInformation
TheseproceduresexplainhowtoconfiguretheValidationApplicationBlockwiththeconfigurationtools.TheValidationApplicationBlockalsoallowsyoutouseattributesandcodetoperformmanyofthetasksdescribedhere.Forinformationabouthowtouseattributesandcode,seeUsingtheValidationBlockValidators.ForinformationaboutpropertiesthatareassociatedwithvalidatorssuchasTagandMessageTemplate,seeUnderstandingCommonValidatorProperties.
ThisprocedureexplainshowtoaddtheValidationApplicationBlocktotheconfigurationfile.FordetailsoftheschemafortheValidationApplicationBlockconfiguration,seeSourceSchemafortheValidationApplicationBlock.
ToaddtheValidationApplicationBlockbyusingtheconfigurationtool1. Opentheconfigurationfile.Formoreinformation,seeConfiguring
EnterpriseLibrary.2. OpentheBlocksmenuandthenclickAddValidationSettings.3. (Optional)Ifyouwanttoencrypttheconfigurationfile,clickthe
chevronexpanderarrowtoshowtheproperties,andthenselectaprotectionproviderfromthedrop-downlistintheProtectionProviderfield.
Thenextprocedureshowshowtodefinearulesetforthemembersofatype.ItassumesthatyouhavealreadyaddedtheValidationApplicationBlocktoyourconfiguration.Membersofatypethatyouwillvalidatecanbefields,methods,orproperties.Notethatitispossibleforatypetohavemultiplerulesetsassociatedwitheachtypeyouconfigure.Forexample,inthefollowingscreenshot,theProducttypehastworulesets,Ruleset1andRuleset2.
Ruleset1specifiesanotnullvalidatorandaregularexpressionvalidatorfortheIDproperty,andastringlengthvalidatorfortheNameproperty.Ruleset2specifiesanotnullvalidatorandastringlengthvalidatorfortheIDproperty,andarangevalidatorfortheInStockproperty.
![Page 918: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/918.jpg)
Whenyouclickonanitemintheconfigurationtool,relateditemsarehighlightedandlinksappearbetweenthem,asshownfortheProperty:IDiteminthescreenshot.
Todefinearulesetformembersofatypebyusingtheconfigurationtool1. IfthesettingsfortheValidationSettingssectionarenotvisible,click
thechildexpanderarrowtotheleftofValidationSettings.2. ClicktheplussigniconinValidatedTypesandclickAddTypeto
Validate.3. Inthetypeselectordialogbox,expandtheassemblyyouwanttouse.
Tofilterthelist,typepartofthenameintheTypenameeditbox;forexample,type"string"tofilterforallclassescontainingtheword"string".Iftheassemblyisnotshowninthelist,clickAddfromGAC(theglobalassemblycache)orAddfromFileandnavigatetoit.SelectthetypeyouwanttovalidateandclickOK.
4. Todefinearuleset,right-clickonthetypeintheValidatedTypescolumnandthenclickAddValidationRuleset.ThisaddsarulesetwiththedefaultnameValidationRulesetandaValidatorsitemthatyoucanusetovalidatethetypeitself.
5. EdittheNamepropertyoftherulesetasrequired.6. Toaddavalidatorthatappliestoaninstanceofaclassasawhole,
ratherthantoindividualmembersofthatclass,right-clicktheValidatorsitemintheValidationTargetscolumn,pointtoAddValidators,andthenclickthevalidatoryouwanttoapply.Repeatthis
![Page 919: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/919.jpg)
steptoaddadditionalvalidatorsthatwillbeappliedatthetypelevelifrequired.Typicallyyouwillusethisfeatureforonlyanotnullvalidator,objectcollectionvalidator,compositevalidator,oracustomvalidator.
7. Toselecttheindividualmembersofatypetobevalidated,youcanuseeitherofthefollowingmethods:
Right-clickontheheadingoftherulesetitem,andthenclickAddFieldtoValidate,AddMethodtoValidate,orAddPropertytoValidate.Thenenterthenameofthefield,method,orpropertyintheValidationTargetspane.Alternatively,youcanselectseveralmembersofatypesimultaneously.Right-clickontherulesetandclickSelectMembers.IntheMemberSelectordialogbox,selecttheProperties,Methods,and/orFieldsthatyouwanttovalidate,andthenclickOK.
8. Toaddavalidatorforatypemember,right-clicktheheadingofafield,method,orpropertyofamemberforthetypeintheValidationTargetscolumn,pointtoAddValidators,andthenclickthevalidatoryouwanttoapply.Repeatthissteptoaddadditionalvalidatorsthatwillbeappliedtoindividualtypemembersasrequired.
9. Editthepropertiesofeachvalidatoryouaddedtotheconfiguration:(Optional)EditthedefaultNameproperty.Specifythevalidationerrormessage.EntereitheraMessageTemplate(whichmayincludethevalidationmessagetokensdescribedinUnderstandingCommonValidatorProperties),orsettheTemplateResourceNameandTemplateResourceTypepropertiesifyouwanttoloadthemessagetemplatefromaresourcesfile.Tousearesourcesfile,enterthenameoftheresourcefortheTemplateResourceNamethenclickontheellipsisbutton(...)intheTemplateResourceTypepropertyandusethetypeselectortolocateandselecttheresourcesfile.(Optional)Ifyouwantthevalidatortooperateinreverse,sothatthevalidatorwillreturnfalse(failedvalidation)whenthevalidationruleissatisfied,andtrue(noerror)whenthevalidationtestfails,settheNegatedpropertytoTrue.ThedefaultisFalse.(Optional)Ifyouwanttopassanadditionaltextvaluetothe
![Page 920: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/920.jpg)
applicationwhenvalidationfails,enterthistextastheTagproperty.Youcanfiltervalidationresultsonthevaluesyouspecifyforthisproperty.Entervaluesfortheremainingvalidatorproperties.Thepropertiesavailabledifferforeachtypeofvalidator.Foralistofpropertiesforeachtypeofvalidator,seeUsingtheValidationBlockValidators.
ThenextprocedureexplainshowtodefineanAndCompositeValidatororanOrCompositeValidator.CompositevalidatorscontainindividualvalidatorsthatarecombinedwithaBooleanANDorORoperation.Forexample,thefollowingscreenshotshowsanOrcompositevalidatorappliedtotheIDpropertyofatypeinRuleset1.ThevalidationspecifiesthateithertheruledefinedbyapropertycomparisonvalidatorortheruledefinedbyarangevalidatormustbesatisfiedforvalidationoftheIDpropertyvaluetosucceed.
Youcanalsonestcompositevalidatorstocreatecomplexlogicforamember,suchas(AOR(BANDC)).
Todefinecompositevalidators1. Right-clickthememberofthetypeyouwanttovalidate,oronthe
Validatoritemtoaddavalidatorforthetypeitself,andclickAddValidators.ThenclickeitherAddAndCompositeValidatororAddOrCompositeValidator.
2. Right-clicktheAndCompositeValidatorortheOrCompositeValidatoryouadded,pointtoAddValidatorsandthenclickoneofthevalidatorsthatwillbeapartofthecompositevalidator.Repeatthissteptoaddadditionalvalidatorsasrequired.
3. EditthepropertiesoftheAndCompositeValidatorortheOrCompositeValidator,andeditthepropertiesofeachvalidatoryouaddtothecompositevalidator:
(Optional)EditthedefaultNameproperty.
![Page 921: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/921.jpg)
Specifythevalidationerrormessage.EntereitheraMessageTemplate(whichmayincludethevalidationmessagetokensdescribedinUnderstandingCommonValidatorProperties),orsettheTemplateResourceNameandTemplateResourceTypepropertiesifyouwanttoloadthemessagetemplatefromaresourcesfile.Tousearesourcesfile,enterthenameoftheresourcefortheTemplateResourceNamethenclickontheellipsisbutton(...)intheTemplateResourceTypepropertyandusethetypeselectortolocateandselecttheresourcesfile.(Optional)Ifyouwantthevalidatortooperateinreverse,sothatthevalidatorwillreturnfalse(failedvalidation)whenthevalidationruleissatisfied,andtrue(noerror)whenthevalidationtestfails,settheNegatedpropertytoTrue.ThedefaultisFalse.(Optional)Ifyouwanttopassanadditionaltextvaluetotheapplicationwhenvalidationfails,enterthistextastheTagproperty.Entervaluesfortheremainingvalidatorproperties.Thepropertiesavailabledifferforeachtypeofvalidator.Foralistofpropertiesforeachtypeofvalidator,seeUsingtheValidationBlockValidators.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 922: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/922.jpg)
MicrosoftEnterpriseLibrary5.0
SourceSchemafortheValidationApplicationBlock
ThistopicliststheelementsandattributesusedtoconfiguretheValidationApplicationBlock.Theconfigurationfilehasthefollowingsection-handlerdeclaration:XML
<configSections>
<sectionname="validation"
type="Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings,
Microsoft.Practices.EnterpriseLibrary.Validation"/>
</configSections>
Thesection-handlerdeclarationcontainsthenameoftheconfigurationsettingssectionandthenameofthesection-handlerclassthatprocessesconfigurationdatainthatsection.Thenameoftheconfigurationsettingssectionisvalidation.Thenameofthesection-handlerclassisMicrosoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings
![Page 923: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/923.jpg)
validationElement
![Page 925: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/925.jpg)
typeElement
![Page 926: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/926.jpg)
rulesetElement
![Page 927: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/927.jpg)
fieldsElement
![Page 928: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/928.jpg)
methodsElement
![Page 929: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/929.jpg)
propertiesElement
![Page 930: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/930.jpg)
validatorElementToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 931: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/931.jpg)
MicrosoftEnterpriseLibrary5.0
AddingApplicationCode
ThefollowingprocedureexplainshowtoincorporatetheValidationApplicationBlockintoyourapplication.
Toprepareyourapplication1. AddareferencetotheValidationApplicationBlockassembly.In
VisualStudio,right-clickyourprojectnodeinSolutionExplorer,andthenclickAddReference.ClicktheBrowsetabandfindthelocationoftheMicrosoft.Practices.EnterpriseLibrary.Validation.dllassembly.Selecttheassembly,andthenclickOKtoaddthereference.
2. Usethesameproceduretosetareferencetothefollowingassemblies:Microsoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.ServiceLocation.dllMicrosoft.Practices.Unity.dllMicrosoft.Practices.Unity.Interception.dll
3. IfyouareusingtheASP.NET,WPF,WindowsForms,orWCFintegrationassemblies,addoneofthefollowingreferencesasappropriate.
Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WinForms.dllMicrosoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet.dllMicrosoft.Practices.EnterpriseLibrary.Validation.Integration.WPF.dllMicrosoft.Practices.EnterpriseLibrary.Validation.Integration.WCF.dll
4. (Optional)TouseelementsfromtheValidationApplicationBlockwithoutfullyqualifyingthetypewiththenamespace,addthefollowingusingstatements(C#)orImportsstatements(VisualBasic)tothetopofyoursourcecodefile.C#
usingMicrosoft.Practices.EnterpriseLibrary.Validation;
usingMicrosoft.Practices.EnterpriseLibrary.Validation.Validators;
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation
![Page 932: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/932.jpg)
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation.Validators
Note:ForVisualBasicprojects,youcanusetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer.OntheProjectmenu,clickProperties.WhentheProjectDesignerappears,clicktheReferencestab.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 933: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/933.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheValidationBlockValidators
TheValidationApplicationBlockincludesclassesnamedvalidators,whichderivefromtheValidatorclass.ThereisagenericversionofthisclassnamedValidator<T>.
Everyvalidatorisassociatedwithaspecifictype.Forexample,theStringLengthValidatorclasscheckstoseeifaSystem.Stringvaluehasalengthwithinapredefinedrange.
Therearefourwaysthatyoucanassociatevalidatorswithyourtypes:Youcanuseconfiguration.Formoreinformation,seeEnteringConfigurationInformation.Youcanuseattributes.Formoreinformation,seeUsingValidationBlockAttributesandUsingDataAnnotationAttributes.Youcanuseacombinationofconfigurationandattributes.Youcanuseselfvalidation,whichmeansthatyouincludevalidationlogicwithintheobjectyouwanttovalidate.Formoreinformation,seeUsingSelfValidation.
Youcanalsoinstantiatevalidatorswithinyourcodewithoutassociatingthemwithaspecifictype.Formoreinformation,seeCreatingValidatorsProgrammatically.
ThefollowingsectionsdescribethevalidatortypesthatareincludedwiththeValidationApplicationBlock.Thesevalidatorsarethefollowing:
AndCompositeValidatorContainsCharactersValidatorDateTimeRangeValidatorDomainValidatorEnumConversionValidatorNotNullValidatorObjectCollectionValidatorObjectValidatorOrCompositeValidatorPropertyComparisonValidatorRangeValidator
![Page 934: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/934.jpg)
RegularExpressionValidatorRelativeDateTimeValidatorStringLengthValidatorTypeConversionValidatorSingleMemberValidators
Eachentrycontainsexamplesforhowtousethevalidatorwithattributesandwithcode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 935: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/935.jpg)
MicrosoftEnterpriseLibrary5.0
AndCompositeValidator
ClassName:AndCompositeValidator
AttributeName:ValidatorCompositionAttribute
Configurationtoolname:AndCompositeValidator
![Page 936: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/936.jpg)
Description
![Page 937: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/937.jpg)
Properties
![Page 938: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/938.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 939: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/939.jpg)
MicrosoftEnterpriseLibrary5.0
ContainsCharactersValidator
ClassName:ContainsCharactersValidator
AttributeName:ContainsCharactersValidatorAttribute
Configurationtoolname:ContainsCharactersValidator
![Page 940: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/940.jpg)
Description
![Page 941: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/941.jpg)
Properties
![Page 942: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/942.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 943: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/943.jpg)
MicrosoftEnterpriseLibrary5.0
DateTimeRangeValidator
ClassName:DateTimeRangeValidator
AttributeName:DateTimeRangeValidatorAttribute
Configurationtoolname:DateTimeRangeValidator
![Page 944: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/944.jpg)
Description
![Page 945: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/945.jpg)
Properties
![Page 946: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/946.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 947: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/947.jpg)
MicrosoftEnterpriseLibrary5.0
DomainValidator
ClassName:DomainValidator<T>
AttributeName:DomainValidatorAttribute
Configurationtoolname:DomainValidator
![Page 948: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/948.jpg)
Description
![Page 949: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/949.jpg)
Properties
![Page 950: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/950.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 951: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/951.jpg)
MicrosoftEnterpriseLibrary5.0
EnumConversionValidator
ClassName:EnumConversionValidator
AttributeName:EnumConversionValidatorAttribute
Configurationtoolname:EnumConversionValidator
![Page 952: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/952.jpg)
Description
![Page 953: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/953.jpg)
Properties
![Page 954: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/954.jpg)
Examples
![Page 955: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/955.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 956: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/956.jpg)
MicrosoftEnterpriseLibrary5.0
NotNullValidator
ClassName:NotNullValidator
AttributeName:NotNullValidatorAttribute
Configurationtoolname:NotNullValidator
![Page 957: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/957.jpg)
Description
![Page 958: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/958.jpg)
Properties
![Page 959: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/959.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 960: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/960.jpg)
MicrosoftEnterpriseLibrary5.0
ObjectCollectionValidator
ClassName:ObjectCollectionValidator
AttributeName:ObjectCollectionValidatorAttribute
Configurationtoolname:ObjectCollectionValidator
![Page 961: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/961.jpg)
Description
![Page 962: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/962.jpg)
Properties
![Page 963: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/963.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 964: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/964.jpg)
MicrosoftEnterpriseLibrary5.0
ObjectValidator
ClassName:ObjectValidator
AttributeName:ObjectValidatorAttribute
Configurationtoolname:ObjectValidator
![Page 965: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/965.jpg)
Description
![Page 966: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/966.jpg)
Properties
![Page 967: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/967.jpg)
Example
![Page 968: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/968.jpg)
DifferencesbetweentheObjectValidatorandtheFactory-CreatedValidatorsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 969: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/969.jpg)
MicrosoftEnterpriseLibrary5.0
OrCompositeValidator
ClassName:OrCompositeValidator
AttributeName:ValidatorCompositionAttribute
Configurationtoolname:OrCompositeValidator
![Page 970: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/970.jpg)
Description
![Page 971: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/971.jpg)
Properties
![Page 972: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/972.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 973: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/973.jpg)
MicrosoftEnterpriseLibrary5.0
PropertyComparisonValidator
ClassName:PropertyComparisonValidator
AttributeName:PropertyComparisonAttribute
Configurationtoolname:PropertyComparisonValidator
![Page 974: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/974.jpg)
Description
![Page 975: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/975.jpg)
Properties
![Page 976: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/976.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 977: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/977.jpg)
MicrosoftEnterpriseLibrary5.0
RangeValidator
ClassName:RangeValidator<T>
AttributeName:RangeValidatorAttribute
Configurationtoolname:RangeValidator
![Page 978: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/978.jpg)
Description
![Page 979: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/979.jpg)
Properties
![Page 980: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/980.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 981: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/981.jpg)
MicrosoftEnterpriseLibrary5.0
RegularExpressionValidator
ClassName:RegexValidator
AttributeName:RegexValidatorAttribute
Configurationtoolname:RegularExpressionValidator
![Page 982: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/982.jpg)
Description
![Page 983: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/983.jpg)
Properties
![Page 984: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/984.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 985: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/985.jpg)
MicrosoftEnterpriseLibrary5.0
RelativeDateTimeValidator
ClassName:RelativeDateTimeValidator
AttributeName:RelativeDateTimeValidatorAttribute
Configurationtoolname:RelativeDateTimeValidator
![Page 986: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/986.jpg)
Description
![Page 987: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/987.jpg)
Properties
![Page 988: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/988.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 989: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/989.jpg)
MicrosoftEnterpriseLibrary5.0
StringLengthValidator
ClassName:StringLengthValidator
AttributeName:StringLengthValidatorAttribute
Configurationtoolname:StringLengthValidator
![Page 990: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/990.jpg)
Description
![Page 991: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/991.jpg)
Properties
![Page 992: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/992.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 993: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/993.jpg)
MicrosoftEnterpriseLibrary5.0
TypeConversionValidator
ClassName:TypeConversionValidator
AttributeName:TypeConversionValidatorAttribute
Configurationtoolname:TypeConversionValidator
![Page 994: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/994.jpg)
Description
![Page 995: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/995.jpg)
Properties
![Page 996: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/996.jpg)
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 997: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/997.jpg)
MicrosoftEnterpriseLibrary5.0
SingleMemberValidators
TheValidationApplicationBlockcontainsthreevalidatorsthatyoucanusetovalidateindividualmembersoftypes,insteadofvalidatingtheentiretypeusingattributesorrulesets.Whilenotacommonscenario,thistechniquemaybeusefulwhenintegratingwithotherframeworkssuchasWPFandWindowsForms.Thethreevalidatorsare:
FieldValueValidator.Usethisvalidatortovalidateafieldofatype.MethodReturnValueValidator.Usethisvalidatortovalidatethereturnvalueofamethodofatype.PropertyValueValidator.Usethisvalidatortovalidatethevalueofapropertyofatype.
Forexample,youcanprogrammaticallycreateavalidatorforaninstanceofaclassnamedMyClassthatvalidatesthevalueofapropertynamedMyPropertyusingaregularexpressionvalidatorasshownhere.C#
ValidatorpropValidator=newPropertyValueValidator<MyClass>("MyProperty",
newRegexValidator("some-regular-expression"));
MyClassmyInstance=newMyClass();
myInstance.MyProperty="Somevalue";
ValidationResultsresults=propValidator.Validate(myInstance);
VisualBasic
DimpropValidatorAsNewPropertyValueValidator(OfMyClass)("MyProperty",_
NewRegexValidator("some-regular-expression"))
DimmyInstanceAsNewMyClass()
myInstance.MyProperty="Somevalue"
DimresultsAsValidationResults=propValidator.Validate(myInstance)
Thatsecondparametertotheconstructoristhevalidatortouseforthepropertyvalue.Youcanalsocreateacompositevalidatorfromacombinationofvalidators,andspecifythiscompositevalidatorinthecodeabove.Asimilar
![Page 998: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/998.jpg)
techniquecanbeusedwiththeFieldValueValidatorandMethodReturnValueValidator.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 999: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/999.jpg)
MicrosoftEnterpriseLibrary5.0
UnderstandingCommonValidatorProperties
ThereareanumberofpropertiesdefinedfortheValidatorclass.ThesepropertiesarealsoexposedbytheValidatorAttributeclass,whichmeansthattheycanbeusedwithanyattributethatderivesfromthisclass.
Thesepropertiesarethefollowing:MessageTemplate.Formoredetails,seeUsingtheMessageTemplateProperty.MessageTemplateResourceNameandMessageTemplateResourceType.Formoredetails,seeUsingtheMessageTemplateResources.Negate.Formoredetails,seeUsingtheNegateProperty.Tag.Formoredetails,seeUsingtheTagProperty.Ruleset.Formoredetails,seeUsingtheRulesetProperty.
![Page 1000: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1000.jpg)
UsingtheMessageTemplateProperty
![Page 1001: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1001.jpg)
UsingtheMessageTemplateResources
![Page 1002: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1002.jpg)
UnderstandingMessageTemplateTokens
![Page 1003: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1003.jpg)
UsingtheNegateProperty
![Page 1004: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1004.jpg)
UsingtheTagProperty
![Page 1005: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1005.jpg)
UsingtheRulesetPropertyToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1006: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1006.jpg)
MicrosoftEnterpriseLibrary5.0
UnderstandingValidationResults
TheValidationResultstypeisacollectionofValidationResultobjects.EachValidationResultobjectcontainsareportthatincludesreferencestotheValidatorinstance,theobjectthatwasvalidated,anderrormessages.
ThefollowingtableliststhepropertiesandmethodsoftheValidationResultscollectionclass.
Member Description
AddAllResults TakesacollectionofValidationResultinstancesandaddsthemtoanexistingValidationResultsinstance.
AddResult CreatesanewValidationResultinstanceandaddsittoanexistingValidationResultsinstance.
Count ReturnsthenumberofValidationResultinstancesinthecollection.
FindAll FiltersaValidationResultsinstanceandeliminatesresultsthatdonotmatchthevalueoftheTagpropertythatwasspecifiedforthevalidator.ThismethodreturnsanewValidationResultsobjectthatcontainstherequiredsetofValidationResultinstancesandleavestheoriginalValidationResultsinstanceunchanged.
IsValid Thispropertyreturnstrueifvalidationsucceededorfalseifvalidationfailed.
ThefollowingtableliststhepropertiesoftheValidationResultclass.
Property Description
Key Thisisanamethatdescribesthelocationofthevalidationresult.Itcontainsthenameofthememberthatisassociatedwiththevalidator.Itisnullifthevalidatorisdefinedatthetypelevel.
NestedVlidationResults Thenestedvalidationresultsforacomposite
![Page 1007: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1007.jpg)
failedvalidation.
Message Thisisamessagethatdescribesthevalidationfailure.
Tag ThisisavaluesuppliedbytheuserastheTagpropertyofthevalidator.Typically,itisusedforcategorizationorfiltering.Thetagcanbesuppliedthroughtheconstructorbutitistypicallyseteitherbyusingapropertyinthevalidationattributesorwithconfiguration.
Target Thisistheobjecttowhichthevalidationrulewasapplied.
Validator Thisisthevalidatorthatperformedthevalidation.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1008: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1008.jpg)
MicrosoftEnterpriseLibrary5.0
HowValidatorsAreCreated
Whentheapplicationblockcreatesavalidator,itusesasetofrequirementstodeterminewhichtypesandmembersofthosetypescanbeassociatedwiththatvalidator.(Memberscanbemethods,properties,andfields.)
Ingeneral,whentheapplicationblockcreatesavalidator,itevaluatestheassociatedtypeanditsmembers.Onlymembersthathavethefollowingcharacteristicscanbeassociatedwithavalidator:
Theymustbepublicmembers.Methodsmustbenon-voidandtakenoparameters.Propertiesmustbereadable.
Selfvalidationhasadifferentsetofrequirements.Theyarethefollowing:Selfvalidationappliesonlytomethods.Aselfvalidationmethodcanbenon-public.Themethodsignaturemustbevoid[method](ValidationResults).Selfvalidationcanapplytoinheritedmethodsbutnottomethodsthatareprivateandinherited.
![Page 1009: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1009.jpg)
CreatingValidatorswithConfiguration
![Page 1010: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1010.jpg)
CreatingValidatorswithAttributesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1011: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1011.jpg)
CopyCode
MicrosoftEnterpriseLibrary5.0
ValidationandInheritance
Ifyouuseinheritance,youneedtoknowhowthevalidationrulesareappliedthroughouttheclasshierarchy.Hereisanexampleofasimplehierarchy,whereclassPreferredCustomerinheritsfromclassCustomer.(Thevalidatorattributesusedintheexample,suchasCustomerNameValidatorrefertocustomvalidatorsandarenotvalidatorsincludedwiththeValidationApplicationBlock.)C#
publicclassCustomer
{
[CustomerNameValidator]
publicstringName
{
get{...}
set{...}
}
[DiscountValidator]
publicvirtualdoubleDiscount
{
get{...}
set{...}
}
}
publicclassPreferredCustomer:Customer
{
[PreferredDiscountValidator]
publicoverridedoubleDiscount
{
get{...}
set{...}
}
}
![Page 1012: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1012.jpg)
VisualBasic
PublicClassCustomer
<CustomerNameValidator()>_
PublicPropertyName(ByVal_nameAsString)
Get
'...
EndGet
Set(ByValvalue)
'...
EndSet
EndProperty
<DiscountValidator()>_
PublicOverridablePropertyDiscount(ByVal_discountAsDouble)
Get
'...
EndGet
Set(ByValvalue)
'...
EndSet
EndProperty
EndClass
PublicClassPreferredCustomer
InheritsCustomer
<PreferredDiscountValidator()>_
OverridesPublicPropertyDiscount(ByVal_discountAsDouble)
Get
'...
EndGet
Set(ByValvalue)
'...
EndSet
EndProperty
![Page 1013: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1013.jpg)
EndClass
Inthisexample,thePreferredCustomerclassderivesfromtheCustomerclass,anditalsooverridestheDiscountproperty.
Therearetworulesforhowvalidatorsworkwithinaclasshierarchy:Ifaderivedclassinheritsamemberanddoesnotoverrideit,themember'svalidatorsfromthebaseclassapplytothederivedclass.Ifaderivedclassinheritsamemberbutoverridesit,themember'sattributesfromthebaseclassdonotapplytothederivedclass.
Inthisexample,theCustomerNameValidatorattributeappliestothePreferredCustomerclass,buttheDiscountValidatorattributedoesnot.Instead,thePreferredDiscountValidatorattributeapplies.
Ifthisisnotthedesiredbehavior,youcanusevalidatorsofbaseclassestocheckinstancesofderivedclasses.Thefollowingcodeexampleshowshowtodothis.ItassumesthatyouhaveresolvedaninstanceoftheValidationApplicationBlockValidatorFactoryclassandstoreditinavariablenamedvalFactory.C#
Validator<Customer>customerValidator=valFactory.CreateValidator<Customer>();
PreferredCustomermyPreferredCustomer=newPreferredCustomer();
//SetpropertiesofPreferredCustomerhere
ValidationResultsr=customerValidator.Validate(myPreferredCustomer);
VisualBasic
DimcustomerValidatorAsValidator(OfCustomer)=valFactory.CreateValidator(OfCustomer)()
DimmyPreferredCustomerAsPreferredCustomer=NewPreferredCustomer()
'SetpropertiesofPreferredCustomerhere
DimrAsValidationResults=customerValidator.Validate(myPreferredCustomer)
ThisexamplevalidatesaPreferredCustomerobject.However,thevalidationisbasedontheattributesoftheCustomerbaseclass.Thevalidationrulesdefined
![Page 1014: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1014.jpg)
onthePreferredCustomerclassarenotapplied.
YoucanusetheCreateValidator(Type)overloadoftheValidatorFactoryclasstocreateavalidatorthatisspecifictoaclassthatyouprovideatruntime.C#
publicValidationResultsCheckObject(objectobj)
{
if(obj!=null)
{
Validatorv=valFactory.CreateValidator(obj.GetType());
returnv.Validate(obj);
}
else
{
returnnull;
}
}
VisualBasic
PublicFunctionValidationResults(ByValobjAsObject)
IfNotobjIsNothingThen
DimvAsValidator=valFactory.CreateValidator(obj.GetType())
Returnv.Validate(obj)
Else
ReturnNothing
EndIf
EndFunction
ThisexamplecreatesavalidatorbasedontheruntimetypeoftheinputargumenttotheCheckObjectmethod.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
![Page 1015: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1015.jpg)
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1016: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1016.jpg)
MicrosoftEnterpriseLibrary5.0
KeyScenarios
ThissectiondescribesthemostcommonsituationsdevelopersmustaddresswhenusingtheValidationApplicationBlock.Thefollowingscenariosareincluded:
ValidatingObjectsCreatingValidatorsProgrammaticallyUsingValidationBlockAttributesUsingDataAnnotationAttributesDefiningAttributesinMetadataClassesUsingSelfValidationIntegratingwithASP.NET,WPF,WindowsForms,andWCF
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1017: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1017.jpg)
MicrosoftEnterpriseLibrary5.0
ValidatingObjects
Youcanvalidateanobjectonceyouhaveobtainedareferencetoavalidationfactoryandattachedthevalidatorsandtherulesets.TheeasiestwaytoobtainareferencetoavalidationfactoryisthroughtheEnterpriseLibrarycontainer,asdescribedinCreatingandReferencingEnterpriseLibraryObjects.Thistopicdemonstratesthefollowingtechniques:
CreatingValidatorInstancesSpecifyingtheLocationofValidationRulesValidatinganObjectValidatingObjectsUsingRuleSets
Note:InpreviousreleasesofEnterpriseLibrary,youcouldusethestaticValidationfacadetovalidateobjectswithoutfirstcreatingavalidator.YoucouldalsousethestaticValidationFactoryclass(asopposedtothereplacementnon-staticValidatorFactoryclass)tocreatevalidatorinstances.Theseapproachesaresupportedinthisreleaseforbackwardscompatibilitywithexistingapplicationcode.However,totakeadvantageofbenefitsavailablewhenusingdependencyinjection,youshouldusethetechniquesdescribedinthissection.Forinformationaboutusingthestaticfacades,seetheEnterpriseLibrarydocumentationonMSDN.
![Page 1018: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1018.jpg)
CreatingValidatorInstances
![Page 1019: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1019.jpg)
SpecifyingtheLocationofValidationRules
![Page 1020: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1020.jpg)
ValidatinganObject
![Page 1021: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1021.jpg)
ValidatingObjectsUsingRuleSetsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1022: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1022.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingValidatorsProgrammatically
Usingattributestocreaterulesetsisonlypossibleifyouhavethesourcecodefortheclassthatyouwanttovalidate.Insomecases,thismaynotbethecase.Anotherteam,orautilitysuchastheWebServicesDescriptionLanguageTool(Wsdl.exe),maycreatetheclass—andyouhaveonlythebinaryassembly.
Inaddition,youmaywanttovalidateindividualvalues,ratherthanentireobjects.Forbothofthesescenarios,youcancreatevalidatorsprogrammatically.Thisisshowninthefollowingcodeexample.C#
Validator<string>emailAddressValidator
=newRegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
ValidationResultsr=emailAddressValidator.Validate(myEmailAddress);
ValidatorshortStringValidator
=newAndCompositeValidator(newNotNullValidator(),newStringLengthValidator(1,5));
shortStringValidator.Validate(myStringValue,r);
VisualBasic
DimemailAddressValidatorAsValidator(OfString)_
=NewRegexValidator("\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
DimrAsValidationResults=emailAddressValidator.Validate(myEmailAddress)
DimshortStringValidatorAsValidator_
=NewAndCompositeValidator(NewNotNullValidator(),NewStringLengthValidator(1,5))
shortStringValidator.Validate(myStringValue,r)
Inthisexample,thefirstlineusesnewtocreateaninstanceoftheRegExValidatorclasswiththeparametervaluesettothe@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"regularexpressionstring.ThevariableemailAddressValidatorcontainsthereferencetothisinstance.ThesecondlineusesnewtocreateaninstanceoftheAndCompositeValidator
![Page 1023: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1023.jpg)
class.ThevariableshortStringValidatorcontainsthereferencetothisinstance.YoucanusetheAndCompositeValidatorclasstocreateacompositevalidator.Inthisexample,thecompositevalidatorcontainsaNotNullValidatorinstanceandaStringLengthValidatorinstance.
AfteryouprogrammaticallycreateaValidatorobject,youcanusetheValidatemethodtovalidateanobjectasdescribedinthetopicValidatingObjects.NoticehowthesecondcalltotheValidatemethodusestheoverloadthatacceptsanexistinginstanceoftheValidationResultsclassandaddsanyvalidationerrorsitfindstothelist.
Asanalternativetocreatingvalidatorsbyexecutingtheconstructor,youcanresolveindividualvalidatorsthroughtheEnterpriseLibraryContainer.Ifyouspecifyanamewhenyouresolvetheinstance,thisisinterpretedasthenameoftherulesetforthatvalidatortousewhenvalidatingobjects.YoumustaddtheValidationBlockExtensiontothecontainertousethisapproach.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1024: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1024.jpg)
MicrosoftEnterpriseLibrary5.0
UsingValidationBlockAttributes
Validationattributes(boththebuilt-inValidationApplicationBlockattributesandthosedescribedinthetopicUsingDataAnnotationAttributes)canbeusedwithvarioustargetsthatincludeclasses,fields,properties,methods,and(inlimitedcases)parameters.Forinformation,seeValidationAttributeTargets.Thereisalsoasetofattributesthatallowyoutochangethebehaviorofotherattributes.ThesearediscussedinValidationModifierAttributes.Youcanalsospecifytheattributesyouwanttouseinaseparatemetadataclass.Formoredetailsofthis,seeDefiningAttributesinMetadataClasses.
![Page 1025: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1025.jpg)
UsingValidationBlockAttributestoDefineValidationRuleSets
![Page 1026: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1026.jpg)
ValidationAttributeTargets
![Page 1027: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1027.jpg)
ValidationModifierAttributesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1028: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1028.jpg)
MicrosoftEnterpriseLibrary5.0
UsingDataAnnotationAttributes
TheSystem.ComponentModel.DataAnnotationsnamespaceinthe.NETFrameworkcontainsaseriesofattributesthatyoucanaddtoyourclassesandclassmemberstosignifymetadatafortheseclassesandmembers.Theyincludearangeofvalidationattributesthatyoucanusetoapplyvalidationrulestoyourclasses,inmuchthesamewayasyoucanwiththeValidationblockattributes.Forexample,thefollowingshowshowyoucanusetheRangeattributetospecifythatthevalueofthepropertynamedOnOrdermustbebetween0and50.C#
[Range(0,50,ErrorMessage="Quantityonordermustbebetween0and50.")]
publicintOnOrder{get;set;}
VisualBasic
<Range(0,50,ErrorMessage:="Quantityonordermustbebetween0and50.")>_
PublicPropertyOnOrder()AsInteger
...
EndProperty
ComparedtothevalidationattributesprovidedwiththeValidationblock,therearesomelimitationswhenusingthevalidationattributesfromtheDataAnnotationsnamespace:
Therangeofsupportedvalidationoperationsislesscomprehensive,thoughtherearesomenewvalidationtypesavailableinversion4.0ofthe.NETFrameworkthatextendtherange.However,somevalidationoperationssuchaspropertyvaluecomparison,enumerationmembershipchecking,andrelativedateandtimecomparisonarenotavailablewhenusingdataannotationvalidationattributes.ThereisnocapabilitytouseOrcomposition,asthereiswiththeOrcompositevalidatorintheValidationApplicationBlock.Theonlycompositionavailablewithdataannotationvalidationattributesisthe
![Page 1029: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1029.jpg)
Andoperation.Youcannotspecifyrulesetsnames,andsoallrulesimplementedwithdataannotationvalidationattributesbelongtothedefaultruleset.Youwillseemoredetailsaboutrulesetslaterinthischapter.Thereisnosimplebuilt-insupportself-validation,asthereisintheValidationblock.
Note:DataAnnotationvalidatorscanonlybeappliedtoproperties.
Youcan,ofcourse,includebothdataannotationandValidationblockattributesinthesameclassifyouwish,andimplementSelfvalidationusingtheValidationblockmechanisminaclassthatcontainsdataannotationvalidationattributes.ThevalidationmethodsintheValidationblockwillprocessbothtypesofattributes.
Formoreinformationaboutdataannotations,seeSystem.ComponentModel.DataAnnotationsNamespace(.NETFrameworkversion3.5)andSystem.ComponentModel.DataAnnotationsNamespace(.NETFrameworkversion4.0).
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1030: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1030.jpg)
MicrosoftEnterpriseLibrary5.0
DefiningAttributesinMetadataClasses
Insomecases,youmaywanttolocateyourvalidationattributes(bothValidationblockattributesand.NETDataAnnotationvalidationattributes)inaseparatefiletotheonethatdefinestheclassthatyouwillvalidate.Thisisacommonscenariowhenyouareusingtoolsthatgeneratetheclassfiles,andwouldthereforeoverwriteyourvalidationattributes.Toavoidthisyoucanlocateyourvalidationattributesinaseparatefilethatformsapartialclassalongwiththemainclassfile.ThisapproachmakesuseoftheMetadataTypeattributefromtheSystem.ComponentModel.DataAnnotationsnamespace.
YouapplytheMetadataTypeattributetoyourmainclassfile,specifyingthetypeoftheclassthatstoresthevalidationattributesyouwanttoapplytoyourmainclassmembers.Youmustdefinethisaspartialclass,asshownhere.Theonlychangetothecontentofthisclasscomparedtotheattributedversionsyousawintheprevioussectionsofthischapteristhatitcontainsnovalidationattributes.C#
[MetadataType(typeof(ProductMetadata))]
publicpartialclassProduct
{
...Existingmembersdefinedhere,butwithoutattributesorannotations...
}
VisualBasic
<MetadataType(GetType(ProductMetadata))>_
PartialPublicClassProduct
...Existingmembersdefinedhere,butwithoutattributesorannotations...
EndClass
Youthendefinethemetadatatypeasanormalclass,exceptthatyoudeclaresimplepropertiesforeachofthememberstowhichyouwanttoapplyvalidationattributes.Theactualtypeofthesepropertiesisnotimportant,andis
![Page 1031: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1031.jpg)
ignoredbythecompiler.TheacceptedapproachistodeclarethemallasoftypeObject.Asanexample,ifyourProductclasscontainstheIDandDescriptionproperties,youcandefinethemetadataclassforitasshownhere.C#
publicclassProductMetadata
{
[Required(ErrorMessage="IDisrequired.")]
[RegularExpression("[A-Z]{2}[0-9]{4}",
ErrorMessage="ProductIDmustbe2capitallettersand4numbers.")]
publicobjectID;
[StringLength(100,ErrorMessage="Descriptionmustbelessthan100chars.")]
publicobjectDescription;
}
VisualBasic
PublicClassProductMetadata
<Required(ErrorMessage:="IDisrequired.")>_
<RegularExpression("[A-Z]{2}[0-9]{4}",_
ErrorMessage:="ProductIDmustbe2capitallettersand4numbers.")>_
PublicIDAsObject
<StringLength(100,ErrorMessage:="Descriptionmustbelessthan100chars.")>_
PublicDescriptionAsObject
EndClass
Formoreinformation,seeMetadataTypeAttributeClassonMSDN.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1032: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1032.jpg)
MicrosoftEnterpriseLibrary5.0
UsingSelfValidation
Selfvalidationallowsyoutoimplementvalidationlogicwithintheclassyouwanttovalidate.UsetheHasSelfValidationattributetomarktheclassthatcontainsthevalidationlogic.UsetheSelfValidationattributetomarkeachSelfvalidationmethodwithinthatclass.Thefollowingcodeexampleshowshowtodothis.C#
usingMicrosoft.Practices.EnterpriseLibrary.Common.Configuration;
usingMicrosoft.Practices.EnterpriseLibrary.Validation;
usingMicrosoft.Practices.EnterpriseLibrary.Validation.Validators;
[HasSelfValidation]
publicclassTemperatureRange
{
privateintmin;
privateintmax;
//...
[SelfValidation]
publicvoidCheckTemperature(ValidationResultsresults)
{
if(max<min)
results.AddResult(newValidationResult("Maxlessthanmin",this,"","",null));
}
}
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Common.Configuration
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation.Validators
![Page 1033: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1033.jpg)
CopyCode
CopyCode
<HasSelfValidation()>_
PublicClassTemperatureRange
PrivateminAsInteger
PrivatemaxAsInteger
'...
<SelfValidation()>_
SubCheckTemperature(ByValresultsAsValidationResults)
Ifmax<minThen
results.AddResult(NewValidationResult("Maxlessthanmin",Me,"","",Nothing))
EndIf
EndSub
EndClass
Inthisexample,theCheckTemperaturemethodprovidesselfvalidation.WhentheValidation.ValidatemethodiscalledonaninstanceofTemperatureRange,theCheckTemperaturemethodisinvoked.
IfyoudonotspecifyarulesetnameintheSelfValidationattribute,theselfvalidationroutineispartofthedefaultruleset.Tospecifyarulesetname,includetheRulesetparameterintheSelfValidationattributeasshownbelow.YoucanincludemorethanoneSelfValidationmethodinaclassanddifferentiatethemusingrulesetnames.C#
[SelfValidation(Ruleset="SimpleRuleset")]
publicvoidValidate(ValidationResultsresults)
{
...
}
VisualBasic
<SelfValidation(Ruleset:="SimpleRuleset")>_
![Page 1034: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1034.jpg)
PublicSubValidate(resultsAsValidationResults)
...
EndSub
EachSelfvalidationmethodmusthaveavoidreturnvalueandtakeaValidationResultsinstanceasitsonlyparameter.TheSelfvalidationmethodshouldupdatetheValidationResultsinstanceafterperformingthevalidationifthevalidationfails.FormoreinformationabouttheValidationResultsclass,seeUnderstandingValidationResults.
IfyouhaveaderivedclassandyouwantittoinherittheSelfvalidationbehaviorofitsbaseclass,youmustmarkboththebaseclassandthederivedclasswiththeHasSelfValidationattribute.TheSelfvalidationmethodsinthebaseclassmustbepublicinorderforthemtobeincludedintheselfvalidationofthederivedclass.
Selfvalidationworksincombinationwithanyvalidatorsthatareassignedtoaclass.Therefore,theValidationResultsforanobjectinstancewillincludeboththeresultsfromtheselfvalidationaswellastheresultsfromvalidatorswithintheclass.Inthefollowingcodeexample,theAddressclassusesself-validation,andthestringZipCodehastheStringLengthValidatorassigned.C#
usingMicrosoft.Practices.EnterpriseLibrary.Common.Configuration;
usingMicrosoft.Practices.EnterpriseLibrary.Validation;
usingMicrosoft.Practices.EnterpriseLibrary.Validation.Validators;
[HasSelfValidation]
publicclassAddress
{
privatestring_zipCode;
[StringLengthValidator(1,10,MessageTemplate="ZipCodeInvalidLength")]
publicstringZipCode
{
get{return_zipCode;}
set{_zipCode=value;}
}
![Page 1035: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1035.jpg)
[SelfValidation]
publicvoidDoValidate(ValidationResultsresults)
{
ValidationResultresult=newValidationResult("ErrorMessage",typeof(Address),"","",null);
ValidationResultresult2=newValidationResult("ErrorMessage2",typeof(Address),"","",null);
results.AddResult(result);
results.AddResult(result2);
}
}
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Common.Configuration
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation.Validators
<HasSelfValidation()>_
PublicClassAddress
Private_zipCodeAsString
<StringLengthValidator(1,10,MessageTemplate:="ZipCodeInvalidLength")>_
PublicPropertyZipCode()AsString
Get
Return_zipCode
EndGet
Set(ByValvalueAsString)
_zipCode=value
EndSet
EndProperty
<SelfValidation()>_
SubDoValidate(ByValresultsAsValidationResults)
DimresultAsNewValidationResult("ErrorMessage",GetType(Address),"","",Nothing)
Dimresult2AsNewValidationResult("ErrorMessage2",GetType(Address),"","",Nothing)
results.AddResult(result)
![Page 1036: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1036.jpg)
results.AddResult(result2)
EndSub
EndClass
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1037: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1037.jpg)
MicrosoftEnterpriseLibrary5.0
IntegratingwithASP.NET,WPF,WindowsForms,andWCF
Integrationallowsyoureusethevalidatorsthatareassociatedwithyourapplicationclasseswhenyouperformvalidationattheuser-interfacelevel(forASP.NET,WPF,andWindowsFormsapplications)oratthemessage-sendinglevelofamulti-tieredapplication(forWCFapplications).ByintegratingtheValidationApplicationBlockwithyourapplications,youcanreuseyourvalidationrulesacrossseverallevelsofyoursystemarchitecture.
TheintegrationprovidedbytheValidationApplicationBlockattheuser-interfaceleveldoesthefollowing:
Itprovidesawaytoassociatepropertiesofvalidatedapplicationobjectswithuser-interfacecontrols.Itprovidesawaytoconvertvaluesfromaninputdatatypetoanapplication-specificdatatype.Forexample,youcanconvertastringinputtoaSystem.DateTimevalue.Ithelpsavoidcodingerrorsintypenamesandpropertynames.Forexample,itthrowsexceptionswhentypenamesorpropertynamescannotbefound.Itdoesnotrequireinstancesofapplicationobjectstobecreatedinorderforvalidatorstobeinvokedattheuser-interfacelevel.Inotherwords,youdonotneedtoinstantiateaCustomerobjectjusttocheckwhetheraninputstringenteredbytheusermeetsthevalidationrequirementsoftheCustomer.Nameproperty.
TheintegrationprovidedbytheValidationApplicationBlockforthemessage-passinglevelallowsyoutovalidateWCFmessages,datacontracts,andparameters.
TheValidationApplicationBlockisdesignedtointegratewitharangeofpresentationtechnologies.Fordetails,seetheflowingtopics:
IntegratingwithASP.NETIntegratingwithWPFIntegratingwithWindowsFormsIntegratingwithWCF
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.
![Page 1038: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1038.jpg)
Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1039: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1039.jpg)
CopyCode
MicrosoftEnterpriseLibrary5.0
IntegratingwithASP.NET
YoucanintegratetheValidationApplicationBlockwithASP.NETapplications.Forexample,youcanusetheapplicationblocktovalidateinformationauserentersintoaWebform.ASP.NETisintegratedwiththeValidationApplicationBlockthroughthetypesdefinedintheMicrosoft.Practices.EnterpriseLibrary.Validation.Integration.AspNetassembly.
ThePropertyProxyValidatorclassdefinedinthisassemblyprovidesthemainintegrationpoint.ItspurposeistocheckanASP.NETcontrol'svalueusingthevalidatorsthatareincludedinauser-providedapplicationclass.ThePropertyProxyValidatorclassactsasawrapperthatlinksacontroltoavalidatorinanapplication-levelclass.
ThePropertyProxyValidatorclassraisestheValueConverteventwhenitneedstoconvertthetypeofavalueenteredintotheassociatededitcontrol.Youcanhandlethiseventtoprovideacustomtypeconverterforconvertingvaluesenteredbytheusertovaluesrequiredbythevalidators.Ifyoudonotspecifyahandler,adefaultconversionisperformedbytheASP.NETTypeConverterservices.
TousethePropertyProxyValidatorcontrol,youmustmanuallyaddthecodetoan.aspxfile,asshowninthefollowingexample.
<cc1:propertyproxyvalidator
id="firstNameValidator"
runat="server"
ControlToValidate="firstNameTextBox"
PropertyName="FirstName"
RulesetName="RuleSetA"
SourceTypeName="BusinessEntities.Customer">
</cc1:propertyproxyvalidator>
TheSourceTypeNameattributeshowninthedesigner-generatedsource
![Page 1040: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1040.jpg)
referencestheCustomerclassdefinedelsewhereintheapplication.Thisistheclasswhosevalidatorswillbeused.
WhenusingASP.NETwiththeValidationApplicationBlock,youmayneedtoconvertdatatypessuchasdatesbeforeyoucanvalidatethedata.Theintegrationlibraryprovidesawayforyoutoinsertcodethatperformsthisconversion.Todothis,youneedtoprovideaneventhandlerfortheconversionandthenreferencethishandlerinthe.aspxfile.Thefollowingcodeexcerptshowsahandlerthatconvertsadateofbirthstringintoadate.C#
usingMicrosoft.Practices.EnterpriseLibrary.Common.Configuration;
usingMicrosoft.Practices.EnterpriseLibrary.Validation;
usingMicrosoft.Practices.EnterpriseLibrary.Validation.Validators;
usingMicrosoft.Practices.EnterpriseLibrary.Validation.Integration;
usingMicrosoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet;
protectedvoiddateOfBirthValidator_ValueConvert(objectsender,ValueConvertEventArgse)
{
stringvalue=e.ValueToConvertasstring;
try
{
e.ConvertedValue=DateTime.Parse(value,System.Globalization.CultureInfo.CurrentCulture);
}
catch
{
e.ConversionErrorMessage="DateOfBirthisnotinthecorrectformat.";
e.ConvertedValue=null;
}
}
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Common.Configuration
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation.Validators
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation.Integration
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet
![Page 1041: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1041.jpg)
ProtectedSubdateOfBirthValidator_ValueConvert(ByValsenderAsObject,ByValeAsValueConvertEventArgs)_
HandlesdateOfBirthValidator.ValueConvert
DimstringValueAsString=CStr(e.ValueToConvert)
DimdateValueAsDateTime
DimsuccessAsBoolean=DateTime.TryParse(stringValue,dateValue)
IfsuccessThen
e.ConvertedValue=dateValue
Else
e.ConversionErrorMessage="DateOfBirthisnotinthecorrectformat."
e.ConvertedValue=Nothing
EndIf
EndSub
ThefollowingcodeshowsthedateOfBirthTextBoxcontrolandthedateOfBirthValidatorinanASP.NETpage.TheOnValueConvertattributeofthePropertyProxyValidatorspecifiesthenameoftheeventhandlershowninthepreviouscode,andislocatedintheassociatedASP.NETcode-behindfile.
<asp:TextBoxID="dateOfBirthTextBox"runat="server"/>
<cc1:PropertyProxyValidatorID="dateOfBirthValidator"runat="server"
ControlToValidate="dateOfBirthTextBox"
PropertyName="DateOfBirth"
RulesetName="RuleSetA"
SourceTypeName="Customer"
OnValueConvert="dateOfBirthValidator_ValueConvert">
</cc1:PropertyProxyValidator>
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1042: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1042.jpg)
MicrosoftEnterpriseLibrary5.0
IntegratingwithWPF
YoucanintegratetheValidationApplicationBlockwithWindowsPresentationFoundation(WPF)applications.Forexample,youcanusetheapplicationblocktovalidatethevaluesinUIcontrolsinaccordancewithrulesdefinedforboundpropertiesofanobject.ValidationisperformedaspartofthegeneralBindingmechanism.ForinformationabouttheWPFbindingmechanism,seeDataBindingOverviewonMSDN.Thevalidationrulesyouspecifycanbeconfiguredtovalidateatdifferentstagesinthebindingprocessingpipeline.Forinformationaboutapplyingvalidationrules,seeHowto:ImplementBindingValidationandValidationStepEnumerationonMSDN.
Note:TheValidationApplicationBlockcannotbeusedinXMLBrowserApplications(XBAP)duetoissueswiththepartialtrustenvironmentthatXBAPmandates.
TousetheWPFintegrationfeature,youmustaddareferencetotheassemblyMicrosoft.Practices.EnterpriseLibrary.Validation.Integration.WPF.TheintegrationisperformedthroughacustomValidationRulenamedValidatorRuledefinedinthisassembly,whichperformsitsvalidationbyinvokingtheValidationApplicationBlockvalidatorforaspecificpropertyonagiventype.Validationonlyoccursifabindingexists,andthatbindingisconnected(ifthesourceofthebindingexists).
Youcanaddavalidationruledirectlytoabindingbyspecifyingthedesiredtypeandpropertynames,asshownhere.XAML
<TextBoxx:Name="TextBox1">
<TextBox.Text>
<BindingPath="ValidatedStringProperty"UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<vab:ValidatorRule
![Page 1043: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1043.jpg)
SourceType="{x:Typetest:ValidatedObject}"
SourcePropertyName="ValidatedStringProperty"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
YoucanalsosettheRulesetNameandValidationSpecificationSourcepropertiestorefinehowthevalidatorforthespecifiedpropertyiscreated.
IfthevalueofthevalidatedcontrolthatcarriestheRequiredvalidationattributeisemptytobeginwith,andremainsemptyduringvalidation,thesourceisnotupdatedandvalidationdoesnotoccur.InthisparticularcasetheValidateOnTargetUpdatepropertywillnotworkeitherbecausethenulldefaultvalueofthetargetwillnotchange.Instead,youcaninvokeUpdateSourceonthebindingtoforcevalidationtooccur,asshownhere.C#
this.Required.GetBindingExpression(TextBox.TextProperty).UpdateSource();
VisualBasic
Me.Required.GetBindingExpression(TextBox.TextProperty).UpdateSource()
ThevalidationruleoperatesintheConvertedProposedValuestep,afterthevaluehasbeenconvertedbutbeforeitissetonthesource.Thismeansthatvalueconversionerrorsmustbedetectedthroughothermechanism.OneapproachistoenabletheValidatesOnDataErrorspropertyonthevalidatedbinding.
![Page 1044: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1044.jpg)
ConfiguringValidationthroughAttachedPropertiesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1045: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1045.jpg)
MicrosoftEnterpriseLibrary5.0
IntegratingwithWindowsForms
YoucanintegratetheValidationApplicationBlockwithWindowsFormsapplications.Forexample,youcanusetheapplicationblocktovalidateinformationauserentersintoaWindowsForm.WindowsFormsisintegratedwiththeValidationApplicationBlockthroughthetypesdefinedintheMicrosoft.Practices.EnterpriseLibrary.Validation.Integration.WinFormsassembly.
TheValidationProviderclassdefinedinthisassemblyprovidesthemainintegrationpoint.ThisclassisanextenderproviderthataddspropertiestoWindowsFormscontrols.ThisproviderallowsyoutospecifyhowtousetheValidationApplicationBlocktovalidatethecontrols'values.
YoucanperformvalidationautomaticallybyusingtheControl.ValidatingeventoryoucaninitiateitinyourcodebyinvokingtheValidationProvider.PerformValidation(Control)method.Inbothcases,youmustusethevalidationprovidertoconfigurethecontrol.
YoucanalsospecifyaninstanceoftheErrorProviderclassforthecontrol.Ifyoudothis,thevalidationerrorsthatresultifthevalidationfailsaresenttotheerrorproviderasaproperlyformattederrormessage.
TheValidationProvider.Enabledpropertyenablesanddisablesthevalidationprovider.Whenitisdisablednovalidationoccurs,thevalidationproviderisconsideredvalid,andanyerrormessagespostedtotheErrorProviderarecleared.Whenitisre-enabled,theprovidercontinuestobevalidanddoesnotpostanyerrormessagesuntilvalidationistriggeredagain.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1046: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1046.jpg)
MicrosoftEnterpriseLibrary5.0
IntegratingwithWCF
WindowsCommunicationFoundation(WCF)providesextensionpointsthatallowyoutosupportcustomscenariossuchascheckingsecurityattributesandperformingpolicyassertions.TheValidationApplicationBlockincludesaWCFintegrationlibrarythataddsacustombehavior,andaparameterinspector.ThisextensionallowstheapplicationblocktovalidateWCFmessages,datacontracts,andparameters.
WhentheWCFservicebegins,itinvokesthecustombehavior.Thiscustombehaviorthenaddstheparameterinspector.WCFcallstheparameterinspectortwiceforeachmessageitprocesses.Thefirsttimeisbeforeitsendsthecalltotheserviceimplementation.Thesecondtimeisaftertheservicegeneratesthereturnmessage.ThissectionexplainshowyoucanusetheValidationApplicationBlockwithyourWCFapplications.Ingeneral,youmustdothefollowing:
IncludetheValidationApplicationBlockinyourservicecontract.Defineabehaviorthatusestheapplicationblock.Defineanendpointthatusesthebehavior.Modifytheservicecontractsothattheclientcanreceiverelevantfailureinformation.Addvalidatorstoparametersasrequired.
![Page 1047: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1047.jpg)
IncludingtheValidationApplicationBlock
![Page 1048: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1048.jpg)
DefiningaBehavior
![Page 1049: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1049.jpg)
DefininganEndpoint
![Page 1050: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1050.jpg)
ReportingValidationFaults
![Page 1051: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1051.jpg)
ValidatingParametersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1052: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1052.jpg)
MicrosoftEnterpriseLibrary5.0
DesignoftheValidationApplicationBlock
TheValidationApplicationBlockisdesignedtodothefollowing:Encapsulatethelogicusedtoperformthemostcommonvalidationtasksintominimalapplicationcode.Relievedevelopersoftherequirementtowriteduplicatecodeandcustomcodeforcommonvalidationtasks.Allowvalidationrulestobechangedaftertheapplicationhasbeendeployed,andensurethatchangeshappensimultaneouslyandconsistently.
![Page 1053: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1053.jpg)
DesignHighlightsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1054: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1054.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingtheValidationApplicationBlock
Initsoriginalstate,theValidationApplicationBlockworkswellfortypicalvalidationscenarios,suchasvalidatingdataforanASP.NETapplication.However,theremaybetimeswhenyouhavetocustomizecertainbehaviorsoftheapplicationblocktobettersuityourapplication'sparticularrequirements.Therearetwowaystodothis.YoucanextendtheValidationApplicationBlockusingthebuilt-inextensionpoints.Youcanalsomodifytheapplicationblockbymakingchangestoitssourcecode.Formoredetails,seethefollowingtopics:
ExtendingtheValidationApplicationBlockExtendingandModifyingEnterpriseLibrary
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1055: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1055.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingtheValidationApplicationBlock
YouextendtheValidationApplicationBlockthroughdesignatedextensionpoints.Typically,thesearecustomclasseswrittenbyyouthatimplementaparticularinterfaceorderivefromanabstractclass.Becausethesecustomclassesexistinyourapplicationspace,youdonothavetomodifyorrebuildtheValidationApplicationBlock;instead,youcandesignateyourextensionsthroughconfigurationsettings.
YoucanextendtheValidationApplicationBlockbyimplementingnewvalidators.YoucancreateyourownValidatorclassesandyourownattributesiftheonesprovidedwiththeValidationApplicationBlockdonotfityourrequirements.Theseclassescouldvalidatedatatypesinnewwaysortheycoulddealwithmorecomplexdatatypes,suchasaCustomerdatatypethatincludesmanydifferentdatatypes.
Thefollowingtableliststhebaseclassesthatyoucanusetoextendtheblock.
CustomProviderorExtension BaseClass
Validator Validator<T>orValidator
ValidatorAttribute ValueValidatorAttribute
YoucanextendtheValidator<T>baseclasstocreatestronglytypedvalidators.YoucanusetheValidatorbaseclasstocreatelooselytypedvalidators.
FordetailedinformationabouthowtointegratecustomproviderswiththeEnterpriseLibraryconfigurationsystemandconfigurationtoolsseeCreatingCustomProvidersforEnterpriseLibrary.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1056: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1056.jpg)
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetoseethattheinitialdeploymentoftheValidationApplicationBlockisplannedandmanagedandthatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheapplicationblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheapplicationblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheapplicationblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheValidationApplicationBlock,seethefollowingtopics:
ValidationApplicationBlockPerformanceCountersValidationApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1057: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1057.jpg)
MicrosoftEnterpriseLibrary5.0
ValidationApplicationBlockPerformanceCounters
ThefollowingtableliststheValidationApplicationBlockperformancecountersandtheirtypes.
PerformanceCounter CounterType
%ValidationSuccesses RawFraction
NumberofValidationCalls NumberOfItems32
NumberofValidationFailures NumberOfItems32
NumberofValidationSuccesses NumberOfItems32
ValidationCalls/sec RateOfCountsPerSecond32
ValidationFailures/sec RateOfCountsPerSecond32
ValidationSuccessesBase RawBase
ValidationSuccesses/sec RateOfCountsPerSecond32
TheseperformancecountersareintheEnterpriseLibraryValidationCounterscategory.Eachperformancecounterhastwoinstances:
AppDomain-Total,whereTotalisallofthetypesthatarevalidatedwithintheapplicationdomain.AppDomain-TypeName,whereTypeNameisthenameofthetypebeingvalidated.
Formoreinformationaboutperformancecounters,seeOverviewofPerformanceMonitoringinthe.NETFrameworkClassLibraryonTechNet.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1058: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1058.jpg)
MicrosoftEnterpriseLibrary5.0
ValidationApplicationBlockEventLogEntries
TheValidationApplicationBlockisinstrumentedtologentriestotheapplicationeventlogifavalidationfails.ThefailureisattributedtoEnterpriseLibraryValidationanditisdescribedasanError.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1059: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1059.jpg)
MicrosoftEnterpriseLibrary5.0
UnityDependencyInjectionandInterception
WelcometoUnity.ThefollowingsectionsofthisguidancedescribethewaysthatyoucanuseUnitydependencyinjectionandUnityinterceptioninyourapplications.Thesectionsare:
WhatIsUnity?WhatDoesUnityDo?WhenShouldIUseUnity?AboutThisReleaseofUnityConfiguringUnity
![Page 1060: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1060.jpg)
UsingUnityinApplicationsDesignofUnityExtendingandModifyingUnityDeploymentandOperationsUnityQuickStarts.ThistopicwalksthroughtheQuickStartapplicationsthatdemonstratehowtoexecutecommonoperationsinyourapplications.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1061: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1061.jpg)
MicrosoftEnterpriseLibrary5.0
WhatIsUnity?
Unityisalightweight,extensibledependencyinjectioncontainerthatsupportsinterception,constructorinjection,propertyinjection,andmethodcallinjection.YoucanuseUnityinavarietyofdifferentwaystohelpdecouplethecomponentsofyourapplications,tomaximizecoherenceincomponents,andtosimplifydesign,implementation,testing,andadministrationoftheseapplications.
Unityisageneral-purposecontainerforuseinanytypeofMicrosoft®.NETFramework-basedapplication.Itprovidesallofthefeaturescommonlyfoundindependencyinjectionmechanisms,includingmethodstoregistertypemappingsandobjectinstances,resolveobjects,manageobjectlifetimes,andinjectdependentobjectsintotheparametersofconstructorsandmethodsandasthevalueofpropertiesofobjectsitresolves.
Inaddition,Unityisextensible.Youcanwritecontainerextensionsthatchangethebehaviorofthecontainer,oraddnewcapabilities.Forexample,theinterceptionfeatureprovidedbyUnity,whichyoucanusetoaddpoliciestoobjects,isimplementedasacontainerextension.
ThefollowingsectionsofthisguidancedescribewhatUnitycando,whenyoushouldchooseUnity,andthewaysthatyoucanuseitinyourapplications:
WhatDoesUnityDo?ThistopicprovidesabriefoverviewthatwillhelpyoutounderstandwhatUnitycando,andexplainssomeoftheconceptsandfeaturesitincorporates.ItalsoprovidesasimpleexampleofthewaythatyoucanwritecodetouseUnity.WhenShouldIUseUnity?ThistopicwillhelpyoutodecideifUnityissuitableforyourrequirements.ItexplainsthebenefitsofusingUnity,andanyalternativetechniquesyoumayconsider.ItalsoprovidesdetailsofanylimitationsofUnitythatmayaffectyourdecisiontouseit.AboutThisReleaseofUnity.Thistopiccontainsinformationaboutthechangesinthisrelease,thetargetaudienceandsystemrequirements,migrationandside-by-sideexecution,andlinkstootherMicrosoftpatterns&practicesresources.ConfiguringUnity.ThistopicdescribeshowyoucanpopulateaUnitycontainerwiththetyperegistrations,mappings,extensions,andother
![Page 1062: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1062.jpg)
informationrequiredbyyourapplication.UsingUnityinApplications.ThistopicexplainshowtouseUnityinyourownapplications.ItexplainshowtoaddUnitytoyourapplication,howtoresolveobjects,andhowtotakeadvantageofthemanyothercapabilitiesofUnity.DesignofUnity.ThistopicexplainsthedecisionsthatwentintodesigningUnityandtherationalebehindthosedecisions.ExtendingandModifyingUnity.ThistopicexplainshowtoextendUnityandhowtomodifythesourcecode.DeploymentandOperations.ThistopicexplainshowtodeployandupdatetheUnityassembliesandusetheinstrumentationexposedbyUnity.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1063: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1063.jpg)
MicrosoftEnterpriseLibrary5.0
WhatDoesUnityDo?
Byusingdependencyinjectionframeworksandinversionofcontrolmechanisms,youcangenerateandassembleinstancesofcustomclassesandobjectsthatcancontaindependentobjectinstancesandsettings.ThefollowingsectionsexplainthewaysthatyoucanuseUnity,andthefeaturesitprovides:
TheTypesofObjectsUnityCanCreateRegisteringExistingTypesandObjectInstancesManagingtheLifetimeofObjectsSpecifyingValuesforInjectionPopulatingandInjectingArrays,IncludingGenericArraysInterceptingCallstoObjects
![Page 1064: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1064.jpg)
TheTypesofObjectsUnityCanCreate
![Page 1065: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1065.jpg)
RegisteringExistingTypesandObjectInstances
![Page 1066: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1066.jpg)
ManagingtheLifetimeofObjects
![Page 1067: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1067.jpg)
ConfiguringTypesforInjectionintoConstructors,Methods,andProperties
![Page 1068: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1068.jpg)
PopulatingandInjectingArrays,IncludingGenericArrays
![Page 1069: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1069.jpg)
InterceptingCallstoObjects
![Page 1070: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1070.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1071: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1071.jpg)
MicrosoftEnterpriseLibrary5.0
WhenShouldIUseUnity?
Dependencyinjectionprovidesopportunitiestosimplifycode,abstractdependenciesbetweenobjects,andautomaticallygeneratedependentobjectinstances.Ingeneral,youshoulduseUnitywhen:
Youwishtobuildyourapplicationaccordingtosoundobjectorientedprinciples(followingthefiveprinciplesofclassdesign,orSOLID),butdoingsowouldresultinlargeamountsofdifficult-to-maintaincodetoconnectobjectstogether.Yourobjectsandclassesmayhavedependenciesonotherobjectsorclasses.Yourdependenciesarecomplexorrequireabstraction.Youwanttotakeadvantageofconstructor,method,orpropertycallinjectionfeatures.Youwanttomanagethelifetimeofobjectinstances.Youwanttobeabletoconfigureandchangedependenciesatruntime.Youwanttointerceptcallstomethodsorpropertiestogenerateapolicychainorpipelinecontaininghandlersthatimplementcrosscuttingtasks.YouwanttobeabletocacheorpersistthedependenciesacrosspostbacksinaWebapplication.
ThefollowingsectionsprovidemoreinformationtohelpyoudecidewhetherUnityissuitableforyourrequirements:
ScenariosforUnityBenefitsofUnityLimitationsofUnity
Note:EnterpriseLibrary,alsofromtheMicrosoftpatterns&practicesgroup,usesUnityasitsprimarymechanismforgeneratinginstancesofEnterpriseLibraryobjects.ForinformationaboutthisandotherfeaturesofEnterpriseLibrary,seetheEnterpriseLibraryCommunitysiteonCodePlex,ortheMicrosoftEnterpriseLibrarypagesonMSDN®.
![Page 1072: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1072.jpg)
ScenariosforUnity
![Page 1073: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1073.jpg)
BenefitsofUnity
![Page 1074: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1074.jpg)
LimitationsofUnityToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1075: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1075.jpg)
MicrosoftEnterpriseLibrary5.0
AboutThisReleaseofUnity
ThissectioncontainsthefollowingtopicsthatwillhelpyoutounderstandthisreleaseofUnityandhelpyouunderstandhowtouseitalongsideearlierversionsormigrateyourapplicationstothisversion.Thissectionincludesthefollowingtopics:
ChangesinThisReleaseTargetAudienceandSystemRequirementsMigrationandSide-by-SideExecutionRelatedpatterns&practicesLinksCopyrightandTermsofUse
![Page 1077: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1077.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1078: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1078.jpg)
MicrosoftEnterpriseLibrary5.0
ChangesinThisRelease
Unity2.0–April2010isanewreleaseoftheMicrosoftpatterns&practicesUnitydependencyinjectionandinterceptionsystem.Thisreleasealsoincludesadditionsinfunctionality,andhasbeenadaptedtoworkwithMicrosoftVisualStudio®2010;andwiththeMicrosoft.NETFrameworkversions3.5SP1and4.0.
GotoCodePlexforinformationonKnownIssues.
ThefollowingsectionsdiscussthechangestoUnity:
BreakingChangestoUnity
ChangesinUnity
![Page 1079: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1079.jpg)
BreakingChangestoUnity
![Page 1080: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1080.jpg)
ChangesinUnityToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1081: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1081.jpg)
MicrosoftEnterpriseLibrary5.0
TargetAudienceandSystemRequirements
Thisguidanceisintendedforsoftwarearchitectsandsoftwaredevelopers.Togetthegreatestbenefitfromthisguidance,youshouldhaveanunderstandingofthefollowingtechnologies:
MicrosoftVisualC#®orMicrosoftVisualBasic.NETMicrosoft.NETFramework
![Page 1082: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1082.jpg)
SystemRequirementsandPrerequisites
![Page 1083: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1083.jpg)
SystemRequirementsforUnityforSilverlightToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1084: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1084.jpg)
MicrosoftEnterpriseLibrary5.0
MigrationandSide-by-SideExecution
Ingeneral,applicationsthatusepreviousversionsofUnitywillfunctionwiththisreleasewithouttheneedforanycodechanges.Itwillbenecessary,however,toupdatethereferencestorefertothenewassembliesandtoupdatetheconfigurationfilestoreferencethecorrectversionoftheassemblies.
ThisversionofUnitycanalsobeinstalledsidebysidewithearlierversions.YoucandeploynewapplicationswrittenforthisversionofUnityalongwithapplicationswrittenforearlierversions.Inaddition,youcanalsochoosetomigrateexistingapplicationstothenewversion.
Ifyoudecidetouseside-by-sideexecution,youmustdeploythedifferentUnityversionsindifferentdirectories.Inanyspecificdirectory,youcannotmixandmatchassembliesfromdifferentversions.
TheshippedprojectfilesusedataintheAssemblyInfo.csfiletobuildassembliesthathavedifferentversioninformation.Thisallowsyoutousestrongnamesandtoadddifferentversionstotheglobalassemblycache(GAC)forside-by-sideexecution.
![Page 1085: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1085.jpg)
PartialMigrationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1086: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1086.jpg)
MicrosoftEnterpriseLibrary5.0
ReusingConfigurationFilesBasedonaPreviousSchema
AlthoughthisdocumentationisbasedontheUnity2.0configurationschemaandallexamplesuseUnity2.0,partialbackwardcompatibilityisprovidedfortheUnity1.2configurationschema.However,youcannotsimplyuseaUnity1.2configurationfile.InordertousethecontentsofaUnity1.2configurationfileyoumust:
1. Createanewconfigurationfile.2. Editthe<configSections>topointtothecorrectassembly.3. Adda<sectionExtension>sectionifyouareusingcontainer
extensionsforUnity.4. CutandpastetheportionsoftheUnity1.2configurationfileyouwish
toreuse.Note:
Checktheresultsasyoustillmaygeterrorsdependinguponthespecificportionsyoucutandpaste.
ForinformationonusingtheUnity1.2configurationschemaseeUnityConfigurationSchematiconMSDN®.
![Page 1087: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1087.jpg)
MigratingCustomExtensionsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1088: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1088.jpg)
MicrosoftEnterpriseLibrary5.0
Relatedpatterns&practicesLinks
ForinformationrelatedtoUnityandothertools,andguidancefordesigningandbuildingapplications,seethepatterns&practiceswebsiteandguides:
Microsoftpatterns&practicesDeveloperCenterMicrosoftApplicationArchitectureGuide,2ndEditionSolutionDevelopmentFundamentalsSecurityGuidanceforApplicationsIndex.NETDataAccessArchitectureGuideImproving.NETApplicationPerformanceandScalabilityMonitoringin.NETDistributedApplicationDesignDeploying.NETFramework-basedApplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1089: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1089.jpg)
MicrosoftEnterpriseLibrary5.0
CopyrightandTermsofUse
Thisdocumentisprovided"as-is".Informationandviewsexpressedinthisdocument,includingURLandotherInternetwebsitereferences,maychangewithoutnotice.Youbeartheriskofusingit.
Someexamplesdepictedhereinareprovidedforillustrationonlyandarefictitious.Norealassociationorconnectionisintendedorshouldbeinferred.
ThisdocumentdoesnotprovideyouwithanylegalrightstoanyintellectualpropertyinanyMicrosoftproduct.Youmaycopyandusethisdocumentforyourinternal,referencepurposes.
©2010Microsoft.Allrightsreserved.
Microsoft,Windows,WindowsServer,WindowsVista,VisualC#,VisualBasic,andVisualStudioaretrademarksoftheMicrosoftgroupofcompanies.Allothertrademarksarepropertyoftheirrespectiveowners.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1090: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1090.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringUnity
OneofthekeytasksyouneedtoperformwhenusingUnityistoconfigurethecontainerwiththerequiredaliases,typeregistrations,mappings,andotherinformationthatitrequiresinordertoresolveobjectsatruntimeandinjecttheappropriateobjectsandvaluesintodependentobjects.ThissectioncoversalloftheconfigurationoptionsforUnity,anddescribeshowyoucanconfigurethecontainerusingaconfigurationfile,oratruntimeusingcode.
UnitycanreadconfigurationinformationfromanXMLconfigurationfile.Bydefault,thisistheApp.configorWeb.configfileforyourapplication.However,youcanloadconfigurationinformationfromanyotherXMLformatfileorfromothersourcesifrequired.
Inaddition,Unityexposesaseriesofmethodsthatyouuseinyourapplicationcodetoconfigurethecontainer.Thisapproachisusefulwhentheregistrationsandmappingsdependontheenvironmentorrun-timeinformation,andyoucanchangetheconfigurationatruntimeusingthesemethods.Run-timeconfigurationisalsoagoodchoiceifyouwanttobeabletomanipulatecontainerhierarchiesatruntimetochangetheoverallbehavioroftyperesolution,injection,andinterception.
Youcan,ofcourse,useacombinationofdesign-time(configurationfiles)andrun-timeconfigurationtoachieveexactlytheconfigurationyourequireatanypointduringapplicationexecution.
TohelpyouunderstandhowtoconfigureUnity,thissectiondividestheinformationintotwoseparatesubsections—onefordesign-timeconfigurationandoneforrun-timeconfiguration.Eachsectioncontainsbasicallythesamesetoftopicsthatdescribespecificconfigurationscenarios.
Note:Theconfigurationfilesarenotencryptedbydefault.Aconfigurationfilemaycontainsensitiveinformationaboutconnectionstrings,userIDs,passwords,databaseservers,andcatalogs.Youshouldprotectthisinformationagainstunauthorizedread/writeoperationsbyusingencryptiontechniques.Ifyouwishtorestrictaccesstotheconfigurationfile,itmustbeencryptedor
![Page 1091: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1091.jpg)
protectedusingAccessControlLists.Itisrecommendedthattheconfigurationstoreisinthesametrustboundaryandthatdecryptingtheconfigurationisdoneinthesametrustboundaryaftertheconfigurationisread.
Thecompletesetoftopicsinthissectionisasfollows:Design-TimeConfiguration
UsingtheConfigurationToolUsingDesign-TimeConfigurationSpecifyingTypesintheConfigurationFileSpecifyingValuesforInjectionExtendingtheUnityConfigurationSchemaConfigurationFilesforInterceptionDefaultAliasesandAssemblies
Run-TimeConfigurationUsingRunTimeConfigurationRegisteringTypesandTypeMappingsCreatingInstanceRegistrationsRegisteringInjectedParameterandPropertyValuesRegisteringGenericParametersandTypesRegisteringContainerExtensionsRegisteringInterception
Forinformationaboutusingcontainerhierarchies,seeUsingContainerHierarchies.ForinformationaboutusingUnity,seeUsingUnityinApplications.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1092: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1092.jpg)
MicrosoftEnterpriseLibrary5.0
Design-TimeConfiguration
ThistopicdescribesthetechniquesyoucanusetoconfigureUnitycontainersusingaconfigurationfileoraconfigurationyouloadintothecontaineratruntime.
Note:ThisdocumentationisbasedontheUnity2.0configurationschemaandallexamplesuseUnity2.0.PartialbackwardcompatibilityisprovidedfortheUnity1.2configurationschema.
ThefollowingtopicsdescribeUnityconfiguration:UsingtheConfigurationTool.NotavailableforUnityconfiguration.UsingtheUnityXSDtoEnableVisualStudioIntelliSense.ThistopicexplainshowtousetheUnityXSDtoenableIntelliSense®inVisualStudiotoassistinmanuallyeditingtheUnityconfiguration.ReusingConfigurationFilesBasedonaPreviousSchema.ThistopicexplainshowtocreateacurrentconfigurationfilebyreusingaconfigurationfilebasedonapreviousUnityschema.UsingDesign-TimeConfiguration.ThistopicexplainstheoverallstructureoftheUnityconfigurationfile,howyouloadconfigurationinformationatruntime,andhowyoucanusealternativeconfigurationsourceswithUnity.SpecifyingTypesintheConfigurationFile.Thistopicexplainshowtoconfiguremappingsinthecontainerbetweentypes.Ingeneral,youwillcreatemappingsbetweenaninterfaceandatypethatimplementstheinterface,orbetweenabaseclassandatypethatinheritsthatbaseclass.YoucanalsousethissectiontospecifyconcretetypesforwhichyouwantUnitytomanagethelifetime.TheUnityConfigurationSchema.ThistopicdescribestheconfigurationschemaelementsforUnity.SpecifyingValuesforInjection.Thistopicexplainshowtoconfigureregistrationsforinstancetypessuchasstring,dateandtime,orinteger
![Page 1093: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1093.jpg)
valuesthatyoucanresolveinyourapplication.ExtendingtheUnityConfigurationSchema.ThistopicexplainshowtoconfigureUnitytoloadandusecontainerextensionsthataddadditionalfunctionalitytothecontainer,andhowyoucanspecifyconfigurationinformationfortheseextensions.ConfigurationFilesforInterception.Thistopicexplainshowtoconfigureinterceptors,behaviors,policies,handlers,andmatchingrulesthatUnitywillusewhencreatinginstancesoftypestowhichyouwanttoaddinterceptioncapabilitiesinordertochangethebehaviorofthatobjectortype.
ForinformationabouthowtoconfigureUnityusingcodethatexecutesatruntimeandcallstheregistrationmethodsoftheUnitycontainer,seeRun-TimeConfiguration.Forinformationaboutresolvingtypesatruntime,seeResolvingObjects.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1094: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1094.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheConfigurationTool
NotavailableforUnityconfiguration.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1095: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1095.jpg)
MicrosoftEnterpriseLibrary5.0
UsingtheUnityXSDtoEnableVisualStudioIntelliSense
YoucanenableIntelliSenseinVisualStudiotoassistthemanualeditingofUnityconfigurationfiles.
Note:TheXSDisnotrequired.Configurationwillworkatruntimewithoutit.ItisonlyrequiredforIntelliSenseinVisualStudio.
InorderfortheXSDtobeusedbytheVisualStudioeditorthe<unity>elementmusthaveanXMLNSattributewiththecorrectnamespace.Thefollowingarethetwowaystogetthecorrectnamespaceinsteadofmanuallyenteringit:
YoucanforcetheeditortousetheschemabyclickingSchemasontheXMLmenuandselectingtheentryfortheunityconfigurationschema.Afterthat,the<unity>elementwillappearasanalternativeintheIntelliSensedropdownandbychoosingitfromIntelliSensethexmlnsattributewillbepopulated.Thisisaper-userandper-projectsetting,soeveryuserworkingontheprojectwouldberequiredtoselectthissetting.Youcanenter<unityxmlns="andthenIntelliSensewillshowalistofnamespaceswhicharetargetedbyaknownschema.Youcanthenchoosetherightnamespace,http://schemas.microsoft.com/practices/2010/unity,whichwillshowupintheIntelliSenselistwhenyouclickonthexmlnsattributeandcompletetheentry.VisualStudiowillthenassociatetheURLwiththeactualphysicalfile.Thisistherecommendedoption,sincethesettingpersistswhenyoupasstheconfigurationfiletoanotheruser.
Collectionelements,suchasaliases,containers,extensions,namespaces,andassembliesarenotsupportedbythexsd,buttheydoworkintheconfigurationfile.
Therearesomepre-definedtypenamesforsometypeattributes,suchasforlifetimemanagers,butthesearejustsuggestionsandanytypenameisaccepted.
Theschemafortheregisterelementimposesaspecificorderforitschildren,an
![Page 1096: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1096.jpg)
orderthatisnotrequiredbytheconfigurationruntimebutmakestheschemamorerobust.Theorderofchildrenisasfollows:oneoptionallifetime,oneoptionalconstructor,andthenasmanyofmethod,property,interceptor,interceptionBehavior,addInterfaceandanycustomelementasdesired,inanyorder.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1097: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1097.jpg)
MicrosoftEnterpriseLibrary5.0
UsingDesign-TimeConfiguration
UsingUnitytypicallyrequirestheconfigurationofaDependencyInjection(DI)container.YoucanconfigureacontainerbyusingtheUnityAPI,a.NETconfigurationfile,ortoalimiteddegreebyusingattributes.ThistopicdescribeshowtouseanXMLconfigurationfiletosupplytherequiredconfigurationinformation..
Dependencyinjectionisaveryflexiblepattern,andtobeusedsuccessfullyrequiresthedevelopertoprovideinformationtothecontainerabouthisapplications.Thetwomostcommonconfigurationtasksaresettinguptypemappingsandconfiguringinjectionofatype.Typemappingsenableyoutorequestatypefromthecontainerthatresultsinthecontainerreturninganinstanceofadifferenttype(typicallyaderivedclassorinterfaceimplementation).Configuringinjectionforatypeentailsspecifyinginformationsuchaswhichconstructorgetscalled,whichpropertiesgetinjected,andwhattheirvaluesare.TheUnityconfigurationschemaencompassesthesetypesofconfigurationandisalsoextensibletoallowforadditionalkindsofconfigurationsuchasUnityinterceptionconfiguration,seeTheUnityConfigurationSchema.Thefollowingsectionsprovidemoredetails:
FormatoftheUnityConfigurationFileLoadingConfigurationFileInformationintoaContainerLoadingtheConfigurationfromAlternativeFiles
![Page 1098: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1098.jpg)
FormatoftheUnityConfigurationFile
![Page 1099: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1099.jpg)
LoadingConfigurationFileInformationintoaContainer
![Page 1100: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1100.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1101: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1101.jpg)
MicrosoftEnterpriseLibrary5.0
SpecifyingTypesintheConfigurationFile
ThistopicexplainshowtousetypesinUnityconfigurationfiles.AtthecoreofUnity'sfunctionalityaretypesandhowyouspecifyandhandlethem.Youwillneedtospecifytypesmanytimesinthetypicalconfigurationfile.Theconfigurationfileshavetheirownsetofrulesforwritingtypenames—rulesthatdifferfromthosefortypeswritteninC#orVisualBasic.TheserulesapplyeverywhereyoucanspecifyatypeintheUnityconfigurationsection.
Thistopiccontainsthefollowingsectionthatdescribehowyoucanspecifytypes:
CLRTypeNamesTypeAliasesAutomaticTypeLookupDefaultAliasesandAssembliesGenericTypes
![Page 1102: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1102.jpg)
CopyCode
CopyCode
CLRTypeNamesYoucanspecifyatypenamebyusingtheCLRstandardtypenamesyntax,asshowninthefollowingexample:
<namespace>.<typename>,<assembly>
Youcanuseeitherpartialassemblynamesorfullyqualifiedassemblynameswhichincludetheculture,version,andpublickeytoken.Thesenamesarestraightforwardforsimpletypes.
Inordertospecifyanameforatypethatisintheglobalassemblycache,youmustusethefullyqualifiedassemblynameforthetypetobecorrectlyloaded.Forexample,forSystem.String,atypeinmscorlib,youcannotuseSystem.String,mscorlib.Youmustusethefullyqualifiedassemblyname,System.String,mscorlib,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089.
CLRtypenamescanbeveryverbose,especiallywhenworkingwithgenerictypes.Forexample,comparethefollowingsimpledictionaryinC#orVisualBasicwiththeCLRexample:C#
Dictionary<string,int>
VisualBasic
Dictionary(OfString,Integer)
CLR
System.Collections.Generic.Dictionary`2[[System.String,mscorlib,2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089],[System.Int32,mscorlib,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089]],mscorlib,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089
Inordertoexpeditetheprocessandmaketypenameslesserrorprone,Unityconfigurationprovidestwooptionsyoucanuseintheconfigurationfile:aliasesandautomatictypelookup.
![Page 1103: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1103.jpg)
TypeAliasesAnaliasissimplyashorthandnamethatwillbereplacedwiththefulltypenamewhenconfigurationisappliedtothecontainer.Youspecifyanaliasintheconfigurationfileinsidethesection,butoutsideany<container>elements,asshowninthefollowingexample:XML
<unityxmlns="http://schemas.microsoft.com/practices/2010/unity">
<aliasalias="MyAlias"type="fulltypename"/>
...
</unity>
Therearethefollowingrulesforusingaliases:Youcanhaveanarbitrarynumberof<alias>elementsintheconfigurationfile.Anywhereyoucangiveatypenameyoucanuseanaliasinstead.Therearenorecursivealiases,whichmeansthatyoucannotuseanaliastodefinethetypeforanalias.Aliasnamesarecasesensitive:<aliasalias="int"/>and<aliasalias="Int"/>aretwodifferentaliasesandarenotinterchangeable.
Note:Aliasesonlyexistatconfigurationtime.Theyarenotavailableatruntime.
![Page 1104: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1104.jpg)
AutomaticTypeLookupInmanycases,likeforILoggerintheFormatoftheUnityConfigurationFileexample,thenameofatypeisallthatisrequired.ButgivenUnity'sdependenceontypesandthelargenumberoftypestypicallyinvolvedinaconfiguration,theabilitytoperformautomatictypelookupsfurtherexpeditestheprocess.Byincorporatingautomatictypelookups,Unityalsoeliminatestheneedtodefineanaliasforeverytypeinanassembly,whichsaveseffortandservestoreducethechanceforerrorfromrepeatedlytypingthenamespaceandassemblyname.
TheUnityconfigurationsystemcansearchfortypes.However,itwillonlylookfortypesifthetypenamespecifiedisnotafulltypenameanditisnotanalias.Youcanprovidetheconfigurationsectionwiththenamespacesandassembliestolookthroughbyusingthe<namespace>and<assembly>elements,asshowninthefollowingexample.XML
<unityxmlns="http://schemas.microsoft.com/practices/2010/unity">
<namespacename="MyApp.Interfaces"/>
<namespacename="System"/>
<assemblyname="MyApp”/>
<assemblyname="mscorlib,2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089"/>
...
</unity>
Withtheconfigurationshowninthepreviousexample,whentheconfigurationsystemhitsanameitdoesnotrecognizeasatypenameoralias,itwillthensearchthroughtheassembliesandnamespacesforamatch.So,tofindILogger,itwilltrytomatchthefollowingnamesinorder:
1. MyApp.Interfaces.ILogger,MyApp2. System.ILogger,MyApp3. MyApp.Interfaces.ILogger,mscorlib,2.0.0.0,Culture=neutral,
PublicKeyToken=b77a5c561934e0894. System.ILogger,mscorlib,2.0.0.0,Culture=neutral,
PublicKeyToken=b77a5c561934e089
![Page 1105: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1105.jpg)
Thesearchwillstopatthefirstmatchingtype.
Thesystemusessimplestringconcatenationtocreatethetypenameitattemptstoload.However,youcannotspecifyanamespacequalifiednameplusthetype,MyApp.Interfaces.ILogger,MyApp,ifyouhaveanynamespaceelementsinyourconfigurationsection,<namespacename="System"/>.Thenamespacefromtheconfigurationsectionwillbeappendedtothenamespace,resultinginasearchonthewrongname,System.MyApp.Interfaces.ILogger.Youshouldputnamespacesinthe<namespace>elementsinsteadofonthetypenamesintheconfigurationfiletoavoidthispossibility.
Ifyouhavealargenumberofassembliesandnamespaces,thenthesystemtypesearchcouldtakeasignificantamountoftimetocomplete.Normally,containersareonlyconfiguredatapplicationstartup,sothistimehitwillnotbesignificantduringtheoperationofyourapplication.Ifyoufinditbecomesasignificantissue,thenyoushouldconsiderusinganexplicitaliasforthetypesthattakethegreatestsearchtimes,sincealiasesarematchedfirst.
Whenmatchinganamewithatype,theconfigurationsystemperformsthefollowingstepsinorder.Thefirstonetosucceedstopstheprocess:
1. Attempttoloadatypeusingthenamedirectly(treatedasafulltypename)
2. Attempttomatchanametoanalias3. Doautomatictypesearch
![Page 1106: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1106.jpg)
DefaultAliasesandAssembliesSometypesandassembliesareusedfrequentlyinUnityconfigurationfiles.TheUnityconfigurationsystemprovidesasetofpredefineddefaultaliasessoyoudonothavetoexplicitlyaddaliasesforthesecommontypes.Anyuser-definedentrieswilloverwritethedefaultones.
Note:Aliasesarecasesensitive.
Inadditiontothedefaultaliases,theUnityconfigurationsystemalsoautomaticallyaddsSystemandmscorlibassembliestothelistofassembliesthataresearchedfortypes.
Thefollowingtablehasthecompletelistofpre-definedtypealiasesprovidedbyUnity:
DefaultAlias Type
sbyte System.SByte
short System.Int16
int System.Int32
integer System.Int32
long System.Int64
byte System.Byte
ushort System.UInt16
uint System.UInt32
ulong System.UInt64
float System.Single
single System.Single
double System.Double
![Page 1107: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1107.jpg)
decimal System.Decimal
char System.Char
bool System.Boolean
object System.Object
string System.String
datetime System.DateTime
DateTime System.DateTime
date System.DateTime
singleton Microsoft.Practices.Unity.ContainerControlledLifetimeManager
ContainerControlledLifetimeManager Microsoft.Practices.Unity.ContainerControlledLifetimeManager
transient Microsoft.Practices.Unity.TransientLifetimeManager
TransientLifetimeManager Microsoft.Practices.Unity.TransientLifetimeManager
perthread Microsoft.Practices.Unity.PerThreadLifetimeManager
PerThreadLifetimeManager Microsoft.Practices.Unity.PerThreadLifetimeManager
external Microsoft.Practices.Unity.ExternallyControlledLifetimeManager
ExternallyControlledLifetimeManager Microsoft.Practices.Unity.ExternallyControlledLifetimeManager
hierarchical Microsoft.Practices.Unity.HierarchicalLifetimeManager
HierarchicalLifetimeManager Microsoft.Practices.Unity.HierarchicalLifetimeManager
resolve Microsoft.Practices.Unity.PerResolveLifetimeManager
perresolve Microsoft.Practices.Unity.PerResolveLifetimeManager
PerResolveLifetimeManager Microsoft.Practices.Unity.PerResolveLifetimeManager
![Page 1108: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1108.jpg)
CopyCode
GenericTypesTheCLRtypenamesyntaxforgenerictypesisextremelyverbose,anditalsodoesnotallowforthingslikealiases.TheUnityconfigurationsystemallowsforashorthandsyntaxforgenerictypesthatalsoallowsforaliasesandtypesearching.
Tospecifyaclosedgenerictype,youprovidethetypenamefollowedbythetypeparametersinacomma-separatedlistinsquarebrackets.
TheUnityshorthandwouldlooklikethefollowingexample.XML
<container>
<registertype="IDictionary[string,int]"</register>
</container>
Ifyouwishtouseanassemblyname-qualifiedtypeasatypeparameter,ratherthananaliasoranautomaticallyfoundtype,youmustplacethatentirenameinsquarebrackets,asshowninthefollowingexample:XML
<registertype="IDictionary[string,[MyApp.Interfaces.ILogger,MyApp]]"/>
Tospecifyanopengenerictypeyousimplyleaveoutthetypeparameters.Youhavetwooptions:
UsetheCLRnotationof`NwhereNisthenumberofgenericparameters.Usethesquarebrackets,withcommas,toindicatethenumberofgenericparameters.
GenericType ConfigurationfileXMLusingCLRnotation
ConfigurationfileXMLusingcommanotation
IList<T> IList`1 IList[]
IDictionary<K,V> IDictionary`2 IDictionary[,]
![Page 1109: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1109.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1110: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1110.jpg)
MicrosoftEnterpriseLibrary5.0
TheUnityConfigurationSchema
Unity2.0usesanewstreamlinedconfigurationschemaforconfiguringUnity.
Thefollowingsectionsdescribetheschemaconfigurationelements,theirchildelements,andtheirattributesinmoredetail:
The<unity>ConfigurationSectionThe<container>ElementThe<register>ElementThe<lifetime>ElementThe<constructor>ElementThe<property>ElementThe<method>ElementThe<param>ElementThe<dependency>ElementThe<value>ElementThe<optional>ElementThe<array>ElementThe<extension>ElementThe<instance>ElementThe<namespace>ElementThe<alias>ElementThe<sectionExtension>Element
![Page 1112: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1112.jpg)
The<register>Element
![Page 1113: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1113.jpg)
The<lifetime>Element
![Page 1114: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1114.jpg)
The<constructor>Element
![Page 1115: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1115.jpg)
The<property>Element
![Page 1116: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1116.jpg)
The<method>Element
![Page 1117: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1117.jpg)
The<param>Element
![Page 1118: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1118.jpg)
The<dependency>Element
![Page 1119: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1119.jpg)
The<value>Element
![Page 1120: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1120.jpg)
The<optional>Element
![Page 1121: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1121.jpg)
The<array>Element
![Page 1122: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1122.jpg)
The<extension>Element
![Page 1123: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1123.jpg)
The<instance>Element
![Page 1124: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1124.jpg)
The<namespace>Element
![Page 1125: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1125.jpg)
The<assembly>Element
![Page 1126: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1126.jpg)
The<alias>Element
![Page 1127: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1127.jpg)
The<sectionExtension>ElementToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1128: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1128.jpg)
MicrosoftEnterpriseLibrary5.0
SpecifyingValuesforInjection
ThistopicexplainshowtoconfiguretheinformationrequiredsothatUnitywillautomaticallypopulateconstructorandmethodparametersandpropertyvalueswhenitresolvesinstancesoftypes.The<param>and<property>elementsbothletyouspecifyavaluetobesuppliedfortheparameterorproperty,respectively.Therearemanydifferentkindsofvaluesthatcanbespecified,eachwithaseparateelement.Inaddition,theUnityconfigurationschemasupportsashorthandnotationforthemostcommoncases.
FormoreinformationabouttheformatoftheUnityconfigurationfile,seeUsingDesign-TimeConfiguration.
Thistopiccontainsthefollowingsectionsdescribingvaluesforinjection:
ResolvingValuesfromtheContainer
GivingValuesinConfiguration
ConfiguringArrayValues
![Page 1129: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1129.jpg)
ResolvingValuesfromtheContainer
![Page 1130: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1130.jpg)
GivingValuesinConfiguration
![Page 1131: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1131.jpg)
ConfiguringArrayValuesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1132: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1132.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingtheUnityConfigurationSchema
TheUnitycontainerishighlycustomizable.Noonefixedconfigurationformatcancovereverythingthatyoumightwanttodowiththecontainer.Asaresult,theUnityconfigurationsystemitselfisextensible,allowingyoutoaddnewvalidelementstoyourconfigurationfile.The<sectionExtension>elementallowsyoutoloadthecodethataddsthesenewoptionstotheconfigurationfile.ThisletsyouspecifyanimplementationoftheSectionExtensiontype.
Sectionextensionscandothefollowingtotheconfiguration:AddnewpredefinedaliasesAddnewcontainer-levelelementsAddnewregistration-levelelementsAddnewvalue-levelelements
Youcancreateyourowncustomextensions,oruseextensionscreatedbythirdparties,withUnity.Unityalsousesdefaultextensionstoimplementitsownfunctionality.Forinformationaboutusingextensions,seeCreatingandUsingContainerExtensions.
OneexampleofasectionextensionistheInterceptionConfigurationExtensionsectionextension,whichshipswiththeUnitypackage.Thissectionextensionaddsthefollowingelementsandaliasestotheschema:
Aliasesaredefinedforeachofthetypes(likeVirtualMethodInterceptor,TransparentProxyInterceptor,andvariousmatchingrules)thatareusedbytheinterceptionconfiguration.The<interception>elementisaddedasavalidelementchildelementforthe<container>element.The<interceptor>,<interceptionBehavior>,<addInterface>,and<policyInjection>elementsareaddedasvalidchildelementsforthe<register>element.
Thisextensionmechanismallowsforalmostunlimitedextensibilityoftheconfigurationfileonanopt-inbasis.Thoughtheschemaextensionwillmodifytheschemaallowedatruntime,itdoesnotmodifytheXSDfileusedbyVisualStudioIntelliSense.Asaresult,youwillstillgetwarningsintheVisualStudio
![Page 1133: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1133.jpg)
XMLeditoreventhoughthefilewillworkfineatruntime.Inordertoresolvethisproblem,thesectionextensionauthormustprovideanupdatedXSDdocumentforusewiththeirextension.Note:
TheInterceptionConfigurationExtensionissupportedbytheschemashippedwithUnity.
The<sectionExtension>elementalsoacceptsauser-providedprefixattribute.Thisisusefulinthecasewheretwosectionextensionsbothprovideextensionelementswiththesamename.Inthecaseofacollision,youcanspecifyaprefixforoneorbothsectionextensions,andthenusethatprefixtodisambiguatethem.
Considertwoschemaextensions,bothofwhichadda<containerCustomization>element.Usingtheprefixattribute,aconfigurationfilethatusesbothwouldlooklikethefollowingexample.XML
<unity>
<sectionExtensionprefix="ext1"type="MyFirstExtension,MyStuff"/>
<sectionExtensionprefix="ext2"type="MySecondExtension,MyOtherStuff"/>
<container>
<ext1.containerCustomization/>
<ext2.containerCustomization/>
</container>
</unity>
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1134: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1134.jpg)
MicrosoftEnterpriseLibrary5.0
ConfigurationFilesforInterception
Unity2.0treatsinterceptionlikeanyextensionyouaddtoUnity.AswithanyextensioninUnity2.0,theUnityinterceptionmechanismcanbeconfiguredthrougheithertheAPIorthroughaUnityconfigurationsection.
Note:Unityprovidespartialbackwardcompatibilityforimplementinginterceptionthroughacontainer.EarlierversionsusedacontainerextensionnamedInterceptionExtension,whichresidesintheassemblynamedMicrosoft.Practices.Unity.Interception.dll.Toconfigureinterception,youspecifythisextensioninthe<extensions>elementofyourapplicationconfiguration,andthendefinethebehaviorofinterceptioninthe<extensionConfig>section.UsingtheextensionandregisterelementsinUnity2.0iscomparabletoInterceptorelementuseintheextensionConfigsectioninearlierversions.Formoreinformationonbackwardcompatibility,seeReusingConfigurationFilesBasedonaPreviousSchema.FormoreinformationaboutUnity1.2interception,seeUsingInterceptionwithUnityonMSDN.
Thistopiccontainsthefollowingsectionstodescribetheinterceptionconfigurationfile:
UsingtheConfigurationFiletoEnableInterceptionStandardInterceptionAliasesEnablingInterceptionofaTypeConfiguringPolicyInjectionPoliciesLegacyInterceptionConfigurationInterceptionConfigurationSchemaElementsRegisteringInterceptionatRunTime
![Page 1135: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1135.jpg)
UsingtheConfigurationFiletoEnableInterception
![Page 1136: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1136.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1137: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1137.jpg)
MicrosoftEnterpriseLibrary5.0
InterceptionConfigurationSchemaElements
Whenconfiguringfilesforinterception,thefollowingelementsmayappearaschildrenofa<register>element.FormoreinformationseeTheregisterElement.Theseelementsareusedtodescribethe<interceptors>and<policies>elements,theirchildelements,andtheirattributesinmoredetail:
The<interceptor>ElementThe<interceptionBehavior>ElementThe<addInterface>ElementThe<interception>ElementThe<policy>ElementThe<matchingRule>ElementThe<callHandler>ElementThe<interceptors>ElementTheinterceptors<interceptor>ElementThe<default>ElementThe<key>Element
Formoreinformationaboutinterception,andselectingtheobjectsandtheirmemberstoaddahandlerpipeline,seeUsingInterceptionandPolicyInjection.
![Page 1138: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1138.jpg)
The<interceptor>Element
![Page 1139: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1139.jpg)
The<interceptionBehavior>Element
![Page 1140: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1140.jpg)
The<addInterface>Element
![Page 1141: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1141.jpg)
The<interception>Element
![Page 1142: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1142.jpg)
The<policy>Element
![Page 1143: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1143.jpg)
The<matchingRule>Element
![Page 1144: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1144.jpg)
The<callHandler>Element
![Page 1145: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1145.jpg)
The<interceptors>Element
![Page 1146: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1146.jpg)
Theinterceptors<interceptor>Element
![Page 1147: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1147.jpg)
The<default>Element
![Page 1148: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1148.jpg)
The<key>ElementToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1149: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1149.jpg)
MicrosoftEnterpriseLibrary5.0
Run-TimeConfiguration
ThistopicexploresthetechniquesyoucanusetoconfigureUnitycontainersusingcodethatexecutesatruntimeandcallstheregistrationmethodsoftheUnitycontainer.Itcontainsthefollowingtopics:
UsingRun-TimeConfiguration.ThistopicdescribesthefluentinterfacethatUnityexposes,andotherissuesyoushouldbeawareofwhenconfiguringthecontaineratruntimeusingcode.RegisteringTypesandTypeMappings.Thistopicexplainshowtoregistermappingsinthecontainerbetweentypes.Ingeneral,youwillcreatemappingsbetweenaninterfaceandatypethatimplementstheinterface,orbetweenabaseclassandatypethatinheritsthatbaseclass.CreatingInstanceRegistrations.Thistopicexplainshowtoregisterexistingobjectsinthecontainerthatyoucanresolveinyourapplication.ThistechniqueisusefulifyouwantUnitytomanagethelifetimeoftheobjectsyouregister.RegisteringInjectedParameterandPropertyValues.ThistopicexplainshowtoregistertheinformationrequiredsothatUnitywillautomaticallypopulateconstructorandmethodparametersandpropertyvalueswhenitresolvesinstancesoftypes.RegisteringGenericParametersandTypes.Thistopicexplainshowyoucanregistertheinformationrequiredforinjectionforgenerictypes,includinggenericarrays.RegisteringContainerExtensions.ThistopicexplainshowtoregisterinformationthatinstructsUnitytoloadandusecontainerextensionsthataddadditionalfunctionalitytothecontainer,andhowyoucanregisterconfigurationinformationfortheseextensions.RegisteringInterception.Thistopicexplainshowtoregisterbehaviors,policies,handlers,andmatchingrulesthatUnitywillusewhencreatinginstancesoftypestowhichyouwanttoaddinterceptioncapabilitiestochangethebehaviorofthatobjectortype.
ForinformationabouthowtoconfigureUnityatdesigntime,includingthetechniquesforloadingconfigurationfromafileorothersource,seeDesign-TimeConfiguration.Forinformationaboutresolvingtypesatruntime,see
![Page 1150: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1150.jpg)
ResolvingObjects.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1151: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1151.jpg)
MicrosoftEnterpriseLibrary5.0
UsingRunTimeConfiguration
Thistopicdiscussessomeofthefactorsyoushouldkeepinmindwhenusingrun-timeconfiguration,andexplainssomefeaturesoftheUnityrun-timeconfigurationmechanism.Fordetailsonhowtospecifyconfigurationusingaconfigurationfile,seeDesign-TimeConfiguration.
![Page 1152: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1152.jpg)
UsingtheUnityContainerFluentInterfaceToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1153: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1153.jpg)
MicrosoftEnterpriseLibrary5.0
RegisteringTypesandTypeMappings
Thistopicexplainshowtoregistertypesinthecontainer.Registeringatypeletsyouconfigurehowthecontainercreatesinstancesofthespecifiedtype.Ingeneral,youwillcreatemappingsbetweenaninterfaceandatypethatimplementstheinterface,orbetweenabaseclassandatypethatinheritsthatbaseclass.However,youcanregistertypesinthecontainerwithoutcreatingamapping.
TheRegisterTypemethodregistersatypewiththecontainer.Attheappropriatetime,thecontainerwillbuildaninstanceofthetypeyouspecify.ThiscouldbeinresponsetodependencyinjectionthroughclassattributesorwhenyoucalltheResolvemethod.Thelifetimeoftheobjectitbuildswillcorrespondtothelifetimeyouspecifyintheparametersofthemethod.Ifyoudonotspecifyavalueforthelifetime,thetypeisregisteredforatransientlifetime,whichmeansthatanewinstancewillbecreatedoneachcalltoResolve.
ThistopiccontainsthefollowingsectionsthatexplainuseoftheRegisterTypemethod:
RegisteringanInterfaceorClassMappingtoaConcreteTypeRegisteringaNamedTypeRegisteringTypeMappingswiththeContainerUsingaLifetimeManagerwiththeRegisterTypeMethodSummaryoftheRegisterTypeMethodOverloadsMoreInformation
![Page 1154: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1154.jpg)
RegisteringanInterfaceorClassMappingtoaConcreteType
![Page 1155: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1155.jpg)
RegisteringaNamedType
![Page 1156: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1156.jpg)
RegisteringTypeMappingswiththeContainer
![Page 1157: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1157.jpg)
UsingaLifetimeManagerwiththeRegisterTypeMethod
![Page 1158: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1158.jpg)
SummaryoftheRegisterTypeMethodOverloads
![Page 1159: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1159.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1160: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1160.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingInstanceRegistrations
Thistopicexplainshowtoregisterexistingobjectsinthecontainerthatyoucanresolveinyourapplication.ThistechniqueisusefulifyoualreadyhaveaninstanceofanobjectthatyouhavepreviouslycreatedandwantUnitytomanageitslifetime,orifyouwantUnitytoinjectthatobjectintootherobjectsthatitisresolving.
TheRegisterInstancemethodregistersanexistinginstancewiththecontainer.Youspecifytheinstancetypeandoptionallifetimeintheparameterlist.Thecontainerwillreturnthespecifiedexistinginstanceforthedurationofthespecifiedlifetime.TheRegisterInstancemethodoverloadsareverysimilartotheRegisterTypemethodoverloads,buttheyacceptanadditionalparameter,theobjectinstancetoregister.Theuseoftheregistrationtypeandanoptionalnameareidenticalforthetwomethods.
Whenresolvingtypeswithdependencies,instancesofobjectsaddedtothecontainerwiththeRegisterInstancemethodactjustlikethoseregisteredthroughRegisterType.TheRegisterTypemethodwithaContainerControlledLifetimeManagerautomaticallygeneratesthissingleinstancethefirsttimeyourcodecallsit,whiletheRegisterInstancemethodacceptsanexistinginstanceforwhichitwillreturnreferences.Ifyoudonotspecifyalifetimemanager,thecontainerwilluseaContainerControlledLifetimeManageranditwillreturnareferencetotheoriginalobjectoneachcalltoResolve.
Thistopiccontainsthefollowingsections,whichexplaintheuseoftheRegisterInstancemethod:
RegisteringanExistingObjectInstanceofanInterfaceorTypetoaContainerUsingaLifetimeManagerwiththeRegisterInstanceMethodSummaryoftheRegisterInstancesMethodOverloadsMoreInformationonUsingtheRegisterInstanceMethod
![Page 1161: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1161.jpg)
RegisteringanExistingObjectInstanceofanInterfaceorTypetoaContainer
![Page 1162: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1162.jpg)
UsingaLifetimeManagerwiththeRegisterInstanceMethod
![Page 1163: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1163.jpg)
SummaryoftheRegisterInstanceOverloads
![Page 1164: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1164.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1165: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1165.jpg)
MicrosoftEnterpriseLibrary5.0
RegisteringInjectedParameterandPropertyValues
ThistopicexplainshowtoconfigureacontainertoperformdependencyinjectionatruntimebyusingtheRegisterTypemethodoverloadswiththeInjectionMembersparameterandavoidrelyingonannotatingtheclassestoresolvewithattributes.ThistopicincludesinformationonconfiguringUnitytoautomaticallypopulateconstructorandmethodparametersandpropertyvalueswhenitresolvesinstancesoftypes.
ThistopiccontainsthefollowingsectionstoexplaintheuseoftheInjectionMembersmethods:
RegisteringInjectionforParametersPropertiesandMethodsUsingInjectionMembersInjectingArraysatRunTimeSummaryoftheInjectionMemberMethodsandOverloadsForMoreInformationonInjectionMembers
![Page 1166: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1166.jpg)
CopyCode
CopyCode
RegisteringInjectionforParameters,Properties,andMethodsusingInjectionMembersTheRegisterTypeoverloadsallowforconfiguringinjectionbyacceptingInjectionMembers.IncludetheInjectionConstructor,InjectionProperty,andInjectionMethodclassesasaRegisterTypeparametertoprovidedependencyinjectionconfigurationinacontainerforInjectionMemberobjects.
ThefollowingexampleshowsthegeneralsyntaxforusinganInjectionMembersubclass,InjectionConstructor,withtheRegisterTypemethod.Inthisexamplethedefaultconstructoriscalled.C#
IUnityContainercontainer=newUnityContainer()
.RegisterType<AType>(newInjectionConstructor());
ATypeaType=container.Resolve<AType>();
VisualBasic
DimcontainerAsIUnityContainer=NewUnityContainer()_
.RegisterType(OfAType)(NewInjectionConstructor())
DimaTypeAsAType=container.Resolve(OfAType)()
YoucanalsouseattributesappliedtotargetclassmemberstoinstructUnitytoinjectdependentobjects.Formoreinformation,seeUsingInjectionAttributes.
YoucanusetheRegisterTypeoverloadstodothefollowing:RegisterConstructorsandParametersSpecifyaPropertyforInjectionSpecifyaMethodforInjection
![Page 1167: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1167.jpg)
RegisterConstructorsandParameters
![Page 1168: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1168.jpg)
SpecifyaPropertyforInjection
![Page 1169: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1169.jpg)
SpecifyaMethodforInjection
![Page 1170: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1170.jpg)
InjectingSpecificArrayInstances
![Page 1171: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1171.jpg)
InjectingAllArrayNamedInstances
![Page 1172: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1172.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1173: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1173.jpg)
MicrosoftEnterpriseLibrary5.0
RegisteringGenericParametersandTypes
Thistopicexplainshowyoucanregistertheinformationrequiredforinjectionforgenerictypes,includinggenericarrays.YoucanspecifyagenerictypewhenyouregisteratypeintheUnitycontainerinalmostexactlythesamewayasyouregisternon-generictypes.Unityprovidestwoclassesspecificallyforregisteringgenerics,GenericParameterforspecifyingthataninstanceofagenerictypeparametershouldberesolved,andGenericResolvedArrayParameterforspecifyingthatanarraycontainingtheregisteredinstancesofagenerictypeparametershouldberesolved.
Seethe"SpecifyingTypesintheConfigurationFile"sectionintheSpecifyingTypesintheConfigurationFiletopicformoredetailsongenerics,includingadiscussionofunbounded,closed,andopengenerictypes.
Thistopiccontainsthefollowingsectionsthatexplainregisteringgenerics:RegisteringGenericInterfacesandClassesRegisteringTypeMappingsForGenericsRegisteringGenericArraysSupportforGenericDecoratorChainsMethodsforRegisteringGenericParametersandTypesMoreInformation
![Page 1174: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1174.jpg)
RegisteringGenericInterfacesandClasses
![Page 1175: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1175.jpg)
RegisteringTypeMappingsforGenerics
![Page 1176: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1176.jpg)
RegisteringGenericArrays
![Page 1177: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1177.jpg)
MethodsforRegisteringGenericParametersandTypes
![Page 1178: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1178.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1179: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1179.jpg)
MicrosoftEnterpriseLibrary5.0
RegisteringContainerExtensions
ThistopicexplainshowtoregisterinformationthatinstructsUnitytoloadandusecontainerextensionsthataddadditionalfunctionalitytothecontainer,andhowyoucanregisterconfigurationinformationfortheseextensions.
Thistopiccontainsthefollowingsectionsthatexplaincontainerextensions:AddingandRemovingExtensionsAccessingConfigurationInformationforExtensionsMethodsforRegisteringandConfiguringContainerExtensionsMoreInformation
![Page 1180: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1180.jpg)
AddingandRemovingExtensions
![Page 1181: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1181.jpg)
AccessingConfigurationInformationforExtensions
![Page 1182: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1182.jpg)
MethodsforRegisteringandConfiguringContainerExtensions
![Page 1183: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1183.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1184: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1184.jpg)
MicrosoftEnterpriseLibrary5.0
RegisteringInterception
Thistopicexplainsrun-timeregistrationofthevariousinterceptionelements,includinginterceptors,behaviors,policies,handlers,andmatchingrulesthatUnityusestoconfigureacontainerforinterception.Theconfigurationinformationisusedwhencreatinginstancesoftypesforwhichyouwanttoaddinterceptioncapabilitiestochangethebehaviorofthatobjectortype.Inordertoprovidebackwardcompatibility,Unity2.0supportscallingtheolderAPISetInterceptorForandSetDefaultInterceptorFormethodsontheInterceptioncontainerextensioninadditiontosupportingtheUnity2.0approachusingtheRegisterTypeAPItoexplicitlyconfigureinterceptors,behaviors,andadditionalinterfaces.
RegisteringInterceptorsandInterceptorBehaviorsExplicitlyUsingRegisterTypeDefaultInterceptorforaTypeRegisteringAdditionalInterfaceRegisteringPolicyInjectionComponents
Forinformationonusingaconfigurationfiletoconfigureacontainerforinterception,seeConfigurationFilesforInterception.
ForinformationonthedesignofUnityinterceptionseeInterceptionwithUnity.
Forinformationonusinginterceptionwithoutadependencyinjection(DI)container,seethe"StandAloneUnityInterception"sectioninUsingInterceptioninApplications.
![Page 1185: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1185.jpg)
CopyCode
CopyCode
RegisteringInterceptorsandInterceptorBehaviorsExplicitlyUsingRegisterTypeUnity2.0enablesinterceptionlikeanyothercontainerextensionbyusingcontainer.AddNewExtension.Thenyoucanconfigureatypeforinterceptionusinganinterceptorofyourchoosing,withbehaviorsofyourchoosing.InUnity2.0youexplicitlyconfigurewhichobjectistobeinterceptedbywhichinterceptionmechanismandspecifythebehaviorbyusingInterceptionBehavior;Unity1.2implicitlysetuppolicyinjectionwhenyouconfiguredaninterceptor.Thefollowingexampleshowshowtoconfigureinterceptionforatypeandturnonacustombehavior.ThisexamplefirstaddstheInterceptionextensionbycallingAddNewExtension,andthenusesRegisterTypetoregisteraVirtualMethodInterceptorandaninterceptionbehavior.Thebehaviormustbedefinedelsewhere.C#
IUnityContainercontainer=newUnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<TypeToIntercept>(
newInterceptor<VirtualMethodInterceptor>(),
newInterceptionBehavior<CustomBehavior>());
VisualBasic
DimcontainerAsIUnityContainer=NewUnityContainer()
container.AddNewExtension(OfInterception)()
container.RegisterType(OfTypeToIntercept)(_
NewInterceptor(OfVirtualMethodInterceptor)(),_
NewInterceptionBehavior(OfCustomBehavior)())
UsingthisoverloadoftheInterceptorconstructoractuallytellsthecontainertoresolvetheinterceptorthroughthecontainer.Youcanpassanoptionalstring,whichbecomesthenametoresolvewith.Inmostapplicationsyouwouldsimplyleavethisblank,butifyouhaveimplementedcustominterceptors,youmightwanttoprovideadditionalconfiguration.ThereisanotheroverloadoftheInterceptorconstructoryoucanusetospecifytheinterceptorsandbehaviors
![Page 1186: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1186.jpg)
CopyCode
CopyCode
bycreatinginstancesandpassingtheactualinstancesintothecontainer,asdoneinthefollowingexample:C#
//Addtheinterceptionextensiontothecontainer
IUnityContainercontainer=newUnityContainer();
container.AddNewExtension<Interception>();
//Configureinterception
container.RegisterType<IInterface,BaseClass>(
"myInterceptor",
newInterceptor(newInterfaceInterceptor()),
newInterceptionBehavior(newCustomBehavior()),
newInterceptionBehavior(newSomeOtherBehavior()));
VisualBasic
'Addtheinterceptionextensiontothecontainer
DimcontainerAsIUnityContainer=NewUnityContainer()
container.AddNewExtension(OfInterception)()
'Configureinterception
container.RegisterType(OfIInterface,BaseClass)_
("myInterceptor",_
NewInterceptor(NewInterfaceInterceptor()),_
NewInterceptionBehavior(NewCustomBehavior()),_
NewInterceptionBehavior(NewSomeOtherBehavior()))
![Page 1188: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1188.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1189: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1189.jpg)
MicrosoftEnterpriseLibrary5.0
RegisteringPolicyInjectionComponents
Thistopicexplainshowtoregisterthevariouselements,includinginterceptors,behaviors,policies,callhandlers,andmatchingrulesthatUnityusestoconfigureacontainerforinterceptionandforapolicyinjectionbehavior.
Whenyouconfigurepolicyinjectionyoumustspecifywhichobjectswillbeinterceptedwiththepolicyinjectionbehaviorandwhichpoliciesinthecontaineraretobeused.Thenwhenbuildingtheobject,thepolicyinjectionbehaviorissetupusingthepoliciesalreadydefinedinthecontainer.
Thistopiccontainsthefollowingsections:PolicyInjectionRun-TimeConfigurationDefiningPoliciesbyUsingtheAPI
![Page 1190: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1190.jpg)
PolicyInjectionRun-TimeConfigurationTherearetwostepstoconfiguringatypeforpolicyinjection.First,youmustregisterthetypeinthecontainer.Inthatregistration,youmustconfigureaninterceptorandenablethePolicyInjectionBehavior.Second,youmustconfigurethepolicyinjectionpoliciesthatdeterminewhichcallhandlersexecuteonwhichmethods.C#
intintercepted=0;
varcontainer=newUnityContainer();
container
.AddNewExtension<Interception>()
.RegisterType<ActionCallHandler>()
//Registerthetypetobeintercepted
.RegisterType<InterceptedType>(
newInterceptor<TransparentProxyInterceptor>(),
newInterceptionBehavior<PolicyInjectionBehavior>())
//Configurepolicies
.Configure<Interception>()
.AddPolicy("policy")
.AddCallHandler(newActionCallHandler(()=>intercepted++))
.AddMatchingRule(newMemberNameMatchingRule("MethodX"));
VisualBasic
DiminterceptedAsInteger=0
Dimcontainer=NewUnityContainer()
container_
.AddNewExtension(OfInterception)()_
.RegisterType(OfActionCallHandler)()_
'Registerthetypetobeintercepted
.RegisterType(OfInterceptedType)(_
NewInterceptor(OfTransparentProxyInterceptor)(),_
NewInterceptionBehavior(OfPolicyInjectionBehavior)())_
'Configurepolicies
.Configure(OfInterception)()_
![Page 1191: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1191.jpg)
.AddPolicy("policy")_
.AddCallHandler(NewActionCallHandler(Function()_
System.Math.Max(System.Threading.Interlocked.Increment_
(intercepted),intercepted-1)))
![Page 1192: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1192.jpg)
DefiningPoliciesbyUsingtheAPIToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1193: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1193.jpg)
MicrosoftEnterpriseLibrary5.0
UsingUnityinApplications
ThistopicdescribeshowtodevelopapplicationsusingUnity,andhowtocreateandbuildinstancesofobjects.ItassumesthatyouunderstandhowtoconfiguretheUnitycontainer.Thissectionincludesthefollowingtopics:
ApplicationDesignConceptswithUnity.ThistopicexplainshowUnitycanhelpyoutoimplementcommondesignpatternsandachievedecouplingandcoherenceinyourdesigns.AddingUnitytoYourApplication.ThistopicdescribeshowtoaddUnitytoyourproject,andhowtoreferencetheappropriateassembliesinyourcode.ResolvingObjects.ThistopiccontainsaseriesofsectionsthatdescribehowyoucanresolveobjectsthroughtheUnitycontainersothatitcreatestheappropriatetypeandoptionallypopulatesanydependenciesspecifiedforthesetypes.UnderstandingLifetimeManagers.ThistopicdescribesthewaythatUnitymanagesthelifetimeofobjectsitcreates,andhowyoucanusethelifetimemanagersincludedwithUnity.UsingContainerHierarchies.ThistopicexplainshowyoucanuseahierarchyofnestedUnitycontainerstoachievefinelygrainedcontrolovertheconfigurationofUnityandmanagethisconfigurationatruntime.
ForinformationonhowtoconfigureUnity,seeConfiguringUnity.
Unityshipsasbothsourcecodeandsignedbinaryassemblies.Youcanusethesignedassembliesdirectly.Ifyouintendtocompilethesourcecode,seeTargetAudienceandSystemRequirements.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1194: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1194.jpg)
MicrosoftEnterpriseLibrary5.0
ApplicationDesignConceptswithUnity
Featuressuchasinversionofcontrol,dependencyinjection,interception,factory,andlifetime(someofwhicharedescribedinthe"ScenariosforUnity"sectionofthetopicWhenShouldIUseUnity?)provideseveralmajoradvantageswhenbuildingapplicationsthatconsistofmanyindividualclassesandcomponents.Designingapplicationsthatconformtothesepatternscanprovidethefollowing:
Thecapabilitytosubstituteonecomponentforanotherusingapluggablearchitecture.Thecapabilitytocentralizeandabstractcommonfeaturesandtomanagecrosscuttingconcernssuchaslogging,authentication,caching,andvalidation.Increasedconfigurationflexibility.Thecapabilitytolocateandinstantiateservicesandcomponents,includingsingletoninstancesoftheseservicesandcomponents.Simplifiedtestabilityforindividualcomponentsandsectionsoftheapplication.Simplifiedoveralldesign,withfasterandlesserror-pronedevelopment.Easeofreuseforcommoncomponentswithinotherapplications.
Ofcourse,implementingthesepatternscaninitiallymakethedesignanddevelopmentprocessmorecomplex,buttheadvantageseasilyjustifythisextracomplexity.Inaddition,theuseofacomprehensivedependencyinjectionmechanismcanactuallymakethetaskofdesigninganddevelopingapplicationsmucheasier.
Fundamentally,therearetwoapproachestousingadependencyinjectionmechanism:
Youcanarrangetohavedependentobjectsautomaticallyinjected,usingtechniquessuchasconstructorinjection,property(setter)injection,andmethodcallinjectionthatinjectdependentobjectsimmediatelywhenyouinstantiatetheparentobject.Thisapproachisgenerallymostappropriateforapplicationsthatrequireapluggablearchitectureorwhereyouwanttomanagecrosscuttingconcerns.Youcanhaveobjectsinjectedonlyondemand,bycallingtheResolve
![Page 1195: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1195.jpg)
methodofthecontaineronlywhenyouneedtoretrieveareferencetoaspecificobject.Thisapproachisknownasservicelocator.Itismoreintrusiveintoyourapplication,butcanbesimplerifyourarchitecturedoesnotlenditselftohavingacentralcontainer.
Inadditiontodependencyinjection,developersmaywishtoimplementpatternssuchasInterception,Decorator,ChainOfResponsibility,andInterceptingFilter,whereacallfromaclientorprocesspassesthroughagraphofobjects,witheachoneabletoaccessandactupondetailsofthecall,suchasthemethodorpropertyname,theparametertypesandvalues,thereturnedtypeandvalue,andotherinformation.Unityachievesthisthroughinterceptionofmethodcalls,providingopportunitiestoapplypoliciestoobjectsusingatechniqueoftenreferredtoaspolicyinjection.
Unityprovidesacomprehensivedependencyinjectionandinterceptionmechanism,andiseasytoincorporateintoyourapplications.However,itdoeschangethewaythatyoudesigntheseapplications.Thefollowingsectionsofthistopicdescribeareaswheredependencyinjectionisuseful:
PluggableArchitecturesManagingCrosscuttingConcernsServiceandComponentLocationPolicyInjectionthroughInterception
![Page 1196: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1196.jpg)
PluggableArchitectures
![Page 1197: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1197.jpg)
ManagingCrosscuttingConcerns
![Page 1198: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1198.jpg)
ServiceandComponentLocation
![Page 1199: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1199.jpg)
PolicyInjectionthroughInterceptionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1200: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1200.jpg)
MicrosoftEnterpriseLibrary5.0
AddingUnitytoYourApplication
Unityisdesignedtosupportarangeofcommonscenariosforresolvinginstancesofobjectsthat,themselves,dependonotherobjectsorservices.However,youmustfirstprepareyourapplicationtouseUnity.Thefollowingproceduredescribeshowtoincludethenecessaryassembliesandelementsinyourcode.
Toprepareyourapplication1. AddareferencetotheUnityassembly.InVisualStudio,right-click
yourprojectnodeinSolutionExplorer,andthenclickAddReference.ClicktheBrowsetabandfindthelocationoftheMicrosoft.Practices.Unity.dllassembly.Selecttheassembly,andthenclickOKtoaddthereference.
2. (Optional)IfyouintendtousetheconfigurationtypeswhenyoucreateextensionsforUnity,usethesameproceduretosetareferencetotheUnityconfigurationassembly,namedMicrosoft.Practices.Unity.Configuration.dll.
3. (Optional)IfyouintendtousetheinterceptionandpolicyinjectionfeaturesofUnity,usethesameproceduretosetareferencetotheUnityinterceptionassembly,namedMicrosoft.Practices.Unity.Interception.dll.
4. (Optional)IfyouintendtousetheconfigurationtypesfortheinterceptionandpolicyinjectionfeaturesofUnity,usethesameproceduretosetareferencetotheUnityinterceptionconfigurationassembly,namedMicrosoft.Practices.Unity.Interception.Configuration.dll.
5. (Optional)TouseelementsfromUnitywithoutfullyqualifyingtheelementreference,addthefollowingusingstatements(C#)orImportsstatements(VisualBasic)tothetopofyoursourcecodefileasrequired.C#
usingMicrosoft.Practices.Unity;
usingMicrosoft.Practices.Unity.Configuration;
usingMicrosoft.Practices.Unity.InterceptionExtension;
![Page 1201: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1201.jpg)
VisualBasic
ImportsMicrosoft.Practices.Unity
ImportsMicrosoft.Practices.Unity.Configuration
ImportsMicrosoft.Practices.Unity.InterceptionExtension
6. (Optional)IfyouareusingtheIServiceLocatorinterface,addareferencetotheservicelocationbinaryMicrosoft.Practices.ServiceLocation.dll.VisualStudiomayautomaticallycopythisfiletoyourbindirectorywhenitcompiles,butyoudonotneedtoincludeitunlessyouareexplicitlyusingtheUnityServiceLocatorAdapterclass.
7. Addyourapplicationcode.FormoreinformationabouthowyoucanuseUnityinyourownapplications,seeWhatDoesUnityDo?
ForVisualBasicprojects,youcanalsousetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer,andthenclickPropertiesontheProjectmenu.WhentheProjectDesignerappears,clicktheReferencestab.
Note:TherearelimitationswhenusingUnityinapartialtrustenvironment.Formoreinformation,seeUsingUnityinPartialTrustEnvironments.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1202: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1202.jpg)
MicrosoftEnterpriseLibrary5.0
ResolvingObjects
YoucanusetheUnitycontainertogenerateinstancesofanyobjectthathasapublicconstructor(inotherwords,objectsthatyoucancreateusingthenewoperator),withoutregisteringamappingforthattypewiththecontainer.WhenyoucalltheResolvemethodandspecifythedefaultinstanceofatypethatisnotregistered,thecontainersimplygeneratesandreturnsaninstanceofthattype.However,theonlytimethatthisisrealisticallypracticaliswhentheobjectyouaregeneratingcontainsdependencyattributesthatthecontainerwillusetoinjectdependentobjectsintotherequestedobject.
TheUnitycontaineridentifiestyperegistrationsandtypemappingsinthecontainerusingatypeand,optionally,aname.Thetypeisaninterfaceoraclass(usuallyaninterfaceorbaseclass)thatthedesiredconcreteobjecttypeimplementsorinherits.ThisidentifiesthemappingsothatthecontainercanretrievethecorrectobjecttypeinresponsetoacalltotheResolveorResolveAllmethod.Wherethereismorethanonemappingforthesametype,theoptionalnamedifferentiatesthesemappingsandallowscodetospecifywhichofthemappingsforthattypetouse.
Theprovisionofbothgenericandnon-genericoverloadsofmanyoftheUnitycontainermethodsensuresthatUnitycanbeusedinlanguagesthatdonotsupportgenerics.Youcanuseeitherapproach(thegenericorthenon-genericoverloads)inyourcodeandmixthemasrequired.Forexample,youcanregistermappingsusingthegenericoverloadsandthenretrieveobjectinstancesusingthenon-genericoverloads,andviceversa.
Note:Whenyouattempttoresolveanabstractbaseclassorinterfacewherethereisnomatchingtypemappinginthecontainer,Unitywillattempttocreateanewinstanceoftheclassyouspecified.Asitcannotconstructandpopulateaninstanceofanabstractclassoraninterface,Unitywillraiseanexception.
Whenyouattempttoresolveanon-mappedconcreteclassthatdoesnothaveamatchingregistrationinthecontainer,Unitywillcreateaninstanceofthatclassandpopulateanydependencies.
![Page 1203: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1203.jpg)
ThefollowingtopicsdescribehowyoucanresolveobjectsusingtheResolveorResolveAllmethods:
ResolvinganObjectbyType.ResolvinganObjectbyTypeandRegistrationName.ResolvingAllObjectsofaParticularType.ResolvingObjectsbyUsingOverridesRetrievingContainerRegistrationInformation
FormoreinformationabouthowyoucanconfigureUnitywithtyperegistrationsandmappings,seeConfiguringUnity.
Formoreinformationabouthowyoucanperformdependencyinjectiononexistingobjectinstances,seeUsingBuildUptoWireUpObjectsNotCreatedbytheContainer.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1204: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1204.jpg)
MicrosoftEnterpriseLibrary5.0
ResolvinganObjectbyType
UnityprovidesamethodnamedResolvethatyoucanusetoresolveanobjectbytype,andoptionallybyprovidingaregistrationname.Registrationsthatdonotspecifyanamearereferredtoasdefaultregistrations.ThistopicdescribeshowtousetheResolvemethodtoresolvetypesandmappingsregisteredasdefaultregistrations.Forinformationaboutresolvingnamedregistrations,seeResolvinganObjectbyTypeandRegistrationName.
![Page 1205: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1205.jpg)
TheResolveMethodOverloadsforDefaultRegistrations
![Page 1206: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1206.jpg)
UsingtheResolveMethodwithDefaultRegistrations
![Page 1207: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1207.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1208: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1208.jpg)
MicrosoftEnterpriseLibrary5.0
ResolvinganObjectbyTypeandRegistrationName
UnityprovidesamethodnamedResolvethatyoucanusetoresolveanobjectbytype,andoptionallybyprovidingaregistrationname.Registrationsthatspecifyanamearereferredtoasnamedregistrations.ThistopicdescribeshowtousetheResolvemethodtoresolvetypesandmappingsregisteredasnamedregistrations.Forinformationaboutresolvingdefaultregistrations,seeResolvinganObjectbyType.
![Page 1209: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1209.jpg)
TheResolveMethodOverloadsforNamedRegistrations
![Page 1210: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1210.jpg)
UsingtheResolveMethodwithNamedRegistrations
![Page 1211: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1211.jpg)
ResolvingGenericTypesbyName
![Page 1212: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1212.jpg)
MoreInformation
![Page 1213: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1213.jpg)
ResolvingGenericTypes
![Page 1214: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1214.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1215: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1215.jpg)
MicrosoftEnterpriseLibrary5.0
ResolvingAllObjectsofaParticularType
Whenyouwanttoobtainalistofalltheregisteredobjectsofaspecifictype,youcanusetheResolveAllmethod.Thetwooverloadsofthismethodaccepteitheraninterfaceoratypename,andtheyreturnaninstanceofIEnumerablethatcontainsreferencestoallregisteredobjectsofthattypethatarenotdefaultmappings.ThelistreturnedbytheResolveAllmethodcontainsonlynamedinstanceregistrations.TheResolveAllmethodisusefulifyouhaveregisteredmultipleobjectorinterfacetypesusingthesametypebutdifferentnames.YoucanalsousetheparamstoprovideconstructoroverridesfortheResolveAllcalls.
![Page 1216: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1216.jpg)
TheResolveAllMethodOverloads
![Page 1217: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1217.jpg)
UsingtheResolveAllMethod
![Page 1218: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1218.jpg)
ResolvingAllGenericTypesbyNameToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1219: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1219.jpg)
MicrosoftEnterpriseLibrary5.0
ResolvingObjectsbyUsingOverrides
Theparameteranddependencyoverrides,ParameterOverrideandDependencyOverride,areResolverOverrideimplementationsthatprovidesupportforoverridingtheregistrationinformationforresolvinginstancesoftypes.WhenyoucalltheResolvemethod,theseclassesenableyoutooverridevaluesspecifiedwhenthetypewasregistered,suchasbyaRegisterTypeorRegisterInstancestatement.Ineffect,RegisterTypesuppliedvaluesareoverriddenbyResolvesuppliedvalues.
UseParameterOverridetooverridethespecifiedconstructorparameterorparameters.TheoverrideapplieseverywheretheparameterappearsunlessyouuseOnTypetoconstraintheoverridetoaspecifiedtype.Sincethepurposeofoverridesistoaffecttheresolutionofdependenciesforallrelevantcreatedobjects,notjusttheobjectrequestedinthecalltoResolve,unconstrainedoverridescanproduceerrorsifthereareunconstrainedParameterOverrideparametersthatmatchparameterswiththesamenamebutdifferenttypesontheselectedconstructorsforobjectscreatedinagivenresolveoperation.
UsePropertyOverridetooverridethevalueofthespecifiedpropertyorproperties.TheoverrideapplieseverywherethepropertyappearsunlessyouuseOnTypetoconstraintheoverridetoaspecifiedtype.
UseDependencyOverridetooverridethevalueinjectedwheneverthereisadependencyofthegiventype.DependencyOverrideoverridesallinstanceswherethetypematches.Bothparameteroverridesanddependencyoverridessupportgenerictypesandmultipleoverrides.
Note:IftheoverriddenobjectwaspreviouslycreatedandisaSingleton,theoverrideisignored.ThelifetimemanagertakesprecedenceandSingletonsalwaysreturnthesameinstance.Thecontainerdoesnotstoreareferencefortheoverriddenobject.
Overridesworkwiththeconstructorthatisselectedforthetype,byattributeorconfiguration.Iftheconstructortobeusedisnotidentifiedwithanattributeor
![Page 1220: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1220.jpg)
explicitcontainerconfiguration,thenthedefaultbehavioristhattheconstructorwiththemostparameterswillbeused.
Aparameterandpropertyoverrideneveraffectswhatelementgetsselected.Theyonlycontrolthevalueofthespecifiedparameterorproperty.Youdonotchangewhichconstructoriscalledwithanoverride,andyoudonotchangewhichpropertiesgetsetwithanoverride.
Note:Ifthepropertyisnotsetasadependencythroughattribute,containerAPI,orconfigurationfile,thentheoverridedoesnothing.
Thistopiccontainsthefollowingsectionstoexplainoverridesinmoredetail:UsingParameterOverridesUsingPropertyOverridesUsingDependencyOverridesMoreInformation
![Page 1221: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1221.jpg)
UsingParameterOverrides
![Page 1222: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1222.jpg)
UsingPropertyOverrides
![Page 1223: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1223.jpg)
UsingDependencyOverrides
![Page 1224: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1224.jpg)
MoreinformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1225: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1225.jpg)
MicrosoftEnterpriseLibrary5.0
DeferringtheResolutionofObjects
Unityprovidesatechniquetofacilitateholdingareferencetoanobjectyouneed,butdonotwanttoconstructrightaway.Youwishtodeferresolutionoftheobject.Insteadofcreatingafactoryforthetypeandinjectingthefactoryintoyourclass,thenusingittocreatethetypeyouwantyoucanusethe.NETstandardtypeFunc<T>(C#)orFunc(OfT)(VisualBasic)withtheResolvemethod.Thisreturnsadelegatethat,wheninvoked,callsintothecontainerandreturnsaninstanceofthespecifiedtype(inthiscase,T).
Youcanevencreateadelegateinthiswaywithoutcreatingaregistrationormappingforthespecifiedtypeinthecontainerifyouwish.Becausetheresolveactiononlytakesplacewhenyouinvokethedelegate,subsequentregistrationsaddedtothecontainerareavailablewhenthetargetobjectisresolved.Thismeansthatyoucanmanipulatetheregistrationsandmappingsinthecontaineratanypointbeforeyouresolvethetargetobject(althoughyoucanobviouslyregisterthetypebeforeyoucreatethedelegateifyouprefer).
Forexample,youcancreateadelegateforacomponentnamedMyClass,andthenregisteramappingforitandperformdeferredresolutionwhenrequiredusingthefollowingcode.C#
//CreateaUnitycontainer
IUnityContainermyContainer=newUnityContainer();
//CreateadelegatefortheIMyClassinterfacetype
varresolver=myContainer.Resolve<Func<IMyClass>>();
//...othercodehere...
//RegisteramappingfortheIMyClassinterfacetotheMyClasstype
myContainer.RegisterType<IMyClass,MyClass>();
//Resolvethemappedtargetobject
IMyClassmyClassInstance=resolver();
![Page 1226: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1226.jpg)
VisualBasic
'CreateaUnitycontainer
DimmyContainerAsIUnityContainer=NewUnityContainer()
'CreateadelegatefortheIMyClassinterfacetype
Dimresolver=myContainer.Resolve(OfFunc(OfIMyClass))()
'...othercodehere...
'RegisteramappingfortheIMyClassinterfacetotheMyClasstype
myContainer.RegisterType(OfIMyClass,MyClass)()
'Resolvethemappedtargetobject
DimmyClassInstanceAsIMyClass=resolver()
YoucanusethisapproachwhenyouresolvethetypeusingtheResolvemethod,oryoucanspecifythedelegatewhenyouconfigureconstructor,propertysetter,ormethodcallinjection.Youcanalsousenamed(non-default)registrationsbyincludingtheregistrationnameinthecalltotheResolvemethodandtheRegisterTypemethod,justasyouwouldwhenusingthesemethodsfornon-deferredresolution.
Inaddition,youcanusethisfeaturetoperformdeferredresolutionofmultiplenamedregistrations,asanalternativetousingtheResolveAllmethod.Forexample,ifyouhavemultiplenamedregistrationsfortheIMyClassinterfacetosuitableconcretetypes,youcanobtainacollectionoftheresolvedtypes.Thefollowingcodeillustratesthis.C#
//CreateaUnitycontainer
IUnityContainermyContainer=newUnityContainer();
//CreateanIEnumerableresolverfortheIMyClassinterfacetype
varresolver=myContainer.Resolve<Func<IEnumerable<IMyClass>>>();
//...othercodehere...
![Page 1227: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1227.jpg)
//RegistermappingsfortheIMyClassinterfacetoappropriateconcretetypes
myContainer.RegisterType<IMyClass,FirstClass>("First");
myContainer.RegisterType<IMyClass,SecondClass>("Second");
myContainer.RegisterType<IMyClass,ThidClass>("Third");
//Resolveacollectionofthemappedtargetobjects
IEnumerable<IMyClass>myClassInstances=resolver();
VisualBasic
'CreateaUnitycontainer
DimmyContainerAsIUnityContainer=NewUnityContainer()
'CreateanIEnumerableresolverfortheIMyClassinterfacetype
Dimresolver=myContainer.Resolve(OfFunc(OfIEnumerable(OfIMyClass)))()
'...othercodehere...
'RegistermappingsfortheIMyClassinterfacetoappropriateconcretetypes
myContainer.RegisterType(OfIMyClass,FirstClass)("First")
myContainer.RegisterType(OfIMyClass,SecondClass)("Second")
myContainer.RegisterType(OfIMyClass,ThidClass)("Third")
'Resolveacollectionofthemappedtargetobjects
DimmyClassInstancesAsIEnumerable(OfIMyClass)=resolver()
Youcanalsousethedeferredresolvertoresolveinstanceregistrations.Forexample,thefollowingcodeshowshowyoucanresolveanIEnumerablecollectionofstringvalues.C#
//CreateaUnitycontainer
IUnityContainermyContainer=newUnityContainer();
//CreateanIEnumerableresolverforstringinstanceregistrations
![Page 1228: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1228.jpg)
varresolver=myContainer.Resolve<Func<IEnumerable<string>>>();
//...othercodehere...
//RegistermappingsfortheIMyClassinterfacetoappropriateconcretetypes
myContainer.RegisterInstance("one","FirstString");
myContainer.RegisterInstance("two","SecondString");
myContainer.RegisterInstance("three","ThirdString");
//Resolveacollectionofthestrings
IEnumerable<string>myStringInstances=resolver();
VisualBasic
'CreateaUnitycontainer
DimmyContainerAsIUnityContainer=NewUnityContainer()
'CreateanIEnumerableresolverforstringinstanceregistrations
Dimresolver=myContainer.Resolve(OfFunc(OfIEnumerable(OfString)))()
'...othercodehere...
'RegistermappingsfortheIMyClassinterfacetoappropriateconcretetypes
myContainer.RegisterInstance("one","FirstString")
myContainer.RegisterInstance("two","SecondString")
myContainer.RegisterInstance("three","ThirdString")
'Resolveacollectionofthestrings
DimmyStringInstancesAsIEnumerable(OfString)=resolver()
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1229: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1229.jpg)
MicrosoftEnterpriseLibrary5.0
RetrievingContainerRegistrationInformation
Youcanretrievealistofregistrationsfromacontainer,andcheckifaspecificregistrationisinthecontainer.
Thistopiccontainsthefollowingsections:ViewingtheContainerRegistrationsandMappingsCheckingfortheExistenceofaSpecificRegistration
![Page 1230: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1230.jpg)
ViewingtheContainerRegistrationsandMappings
![Page 1231: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1231.jpg)
CheckingfortheExistenceofaSpecificRegistrationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1232: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1232.jpg)
MicrosoftEnterpriseLibrary5.0
UsingContainerHierarchies
Unitysupportsnestedcontainers,allowingyoutobuildcontainerhierarchies.Nestingcontainersenablesyoutocontrolthescopeandlifetimeofsingletonobjects,andregisterdifferentmappingsforspecifictypes.Thistopiccontainsthefollowingsectionsthatdescribehowyoucancreatecontainerhierarchiesandusetheminyourapplications:
ConstructingandDisposingUnityContainersControllingObjectScopeandLifetimeRegisteringDifferentMappingsforSpecificTypes
![Page 1233: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1233.jpg)
ConstructingandDisposingUnityContainers
![Page 1234: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1234.jpg)
ControllingObjectScopeandLifetime
![Page 1235: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1235.jpg)
RegisteringDifferentMappingsforSpecificTypesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1236: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1236.jpg)
MicrosoftEnterpriseLibrary5.0
UnderstandingLifetimeManagers
TheUnitycontainermanagesthecreationandresolutionofobjectsbasedonalifetimeyouspecifywhenyouregisterthetypeofanexistingobject,andusesthedefaultlifetimeifyoudonotspecifyalifetimemanagerforyourtyperegistration.
Whenyouregisteratypeinconfiguration,orbyusingtheRegisterTypemethod,thedefaultbehaviorisforthecontainertouseatransientlifetimemanager.Itcreatesanewinstanceoftheregistered,mapped,orrequestedtypeeachtimeyoucalltheResolveorResolveAllmethodorwhenthedependencymechanisminjectsinstancesintootherclasses.Thecontainerdoesnotstoreareferencetotheobject.However,whenyouwantnontransientbehavior(suchasasingleton)forobjectsUnitycreates,thecontainermuststoreareferencetotheseobjects.Itmustalsotakeovermanagementofthelifetimeoftheseobjects.
UnityusesspecifictypesthatinheritfromtheLifetimeManagerbaseclass(collectivelyreferredtoaslifetimemanagers)tocontrolhowitstoresreferencestoobjectinstancesandhowthecontainerdisposesoftheseinstances.
WhenyouregisteranexistingobjectusingtheRegisterInstancemethod,thedefaultbehaviorisforthecontainertotakeovermanagementofthelifetimeoftheobjectyoupasstothismethodusingtheContainerControlledLifetimeManager.Thismeansthatattheendofthecontainerlifetime,theexistingobjectisdisposed.Youcanalsousethislifetimemanagerwhendefiningregistrationsinconfiguration,orwhenusingtheRegisterTypemethod,tospecifythatUnityshouldmanagetheobjectasasingletoninstance.
Usinganon-defaultlifetimemanagerwithRegisterInstancewillresultindifferentbehaviors,dependingonthecontextoftherequests.
ResolverequestsinthesamecontextwheretheRegisterInstancecallwasmade,suchasthesamethreadifusingaper-threadmanager,orthesameparentcontainerwhenusingthehierarchicalone,willreturntheregisteredinstances.Resolverequestsinothercontexts,suchasadifferentthreadifusingaper-threadmanager,orachildcontainerwhenusingthehierarchical
![Page 1237: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1237.jpg)
lifetimemanager,willresultinanewinstancebeingcreatedbythecontaineranditwillbemadethesingletonforthatcontext.Thecreationofaninstanceunderthesecircumstancescouldfailifthecontainercannotresolvetheinstance,forexampleifyouregisteredaninstanceforaninterfacewithnomappingstoamatchingclass.
ForinformationaboutusinglifetimemanagerswiththeRegisterTypeandRegisterInstancemethods,seeRegisteringTypesandTypeMappingsandCreatingInstanceRegistrationsintheRun-TimeConfigurationsectionofthisdocumentation.Forinformationaboutspecifyingthelifetimeofobjectsatdesigntime,seeSpecifyingTypesintheConfigurationFile,andThe<instance>ElementintheDesign-TimeConfigurationsectionofthisdocumentation.
![Page 1238: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1238.jpg)
UnityBuilt-InLifetimeManagers
![Page 1239: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1239.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1240: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1240.jpg)
MicrosoftEnterpriseLibrary5.0
DependencyInjectionwithUnity
Ifyouareusingdependencyinjection(DI)throughaDIcontainerapproachtoyourapplicationdevelopment,youcanuseanyavailableDIcontainerincludingthecontainerprovidedbyUnity.UsingtheUnitydependencyinjectioncontainerprovidesopportunitiesforyoutomoreeasilydecouplecomponents,businessobjects,andservicesyouuseinapplications,andcansimplifyhowyouorganizeandarchitecttheseapplications.
YoucancreateinstancesofobjectsusingtheDIcontainerprovidedbyUnity.Unityisavailableasastand-alonedependencyinjectionmechanism.
Thefollowingsectionsofthistopicwillhelpyoutounderstandtheoverallprocess,anduseUnitydependencyinjectioninyourapplications:
UsingBuildUptoWireUpObjectsNotCreatedbytheContainer.ThistopicexplainshowtouseBuildUptopassexistingobjectinstancesthroughthecontainerinordertoapplydependencyinjectiontothatobject.ThisisanalternativetoresolvingtheobjectusinganyoftheothertechniquesavailablewithUnity.UsingInjectionAttributes.ThistopiccontainsaseriesofsectionsthatdescribehowyoucanuseattributesappliedtomembersoftargetclassestoinstructUnitytoinjectdependentobjectsforconstructorandmethodparameters,andasthevaluesofproperties.CircularReferenceswithDependencyInjection.Thistopicdescribeshowyoushouldbeawareofthepossibilityofcircularreferencesarisingwhenusingdependencyinjectiontechniques.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1241: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1241.jpg)
MicrosoftEnterpriseLibrary5.0
UsingBuildUptoWireUpObjectsNotCreatedbytheContainer
UnityexposesamethodnamedBuildUpthatyoucanusetopassexistingobjectinstancesthroughthecontainerinordertoapplydependencyinjectiontothatobject.ThisisanalternativetoresolvingtheobjectusinganyoftheothertechniquesavailablewithUnity.However,rememberthattheBuildUpmethodcannotinjectdependentobjectsintoconstructorparameters,becausetheobjecthasalreadybeencreated;itisnotcreatedbyUnity.
TheBuildUpmethodisusefulwhenyoudonothavecontroloftheconstructionofaninstance,butyoustillwantpropertyormethodcallinjectionperformed.Forexample,ASP.NETpages,WindowsCommunicationFoundation(WCF)applications,andXAMLcodeoftencreateinstancesofobjectsandpassareferencetoyourcode.TheBuildUpmethodwillusuallyreturntheoriginalobjectafterpassingitthroughthecontainer,althoughcontainerextensionsmayaddotherfeaturesthatcausethemethodtoreturnadifferentobjectthatistype-compatiblewiththeexistingobject.Forexample,aninjectionstrategymaycreateandreturnaproxyforanobjectoraderivedobjectinsteadoftheactualobject.
IfyouhavecreatedoraddedextensionstotheUnitycontainer,theseextensionscanaccessanduseanamethatyouspecifywhenyouexecutetheBuildUpmethod.Thisallowstheextensionstochangetheirbehavior,dependingonthevalueyouspecify.Forexample,theymayusethenametocontrolhowdependenciesareresolvedortocontrolfeaturessuchaseventwiringorinterception.Theactualbehaviordependsontheindividualextension.
![Page 1242: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1242.jpg)
TheBuildUpMethodOverloads
![Page 1243: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1243.jpg)
UsingtheBuildUpMethod
![Page 1244: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1244.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1245: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1245.jpg)
MicrosoftEnterpriseLibrary5.0
UsingInjectionAttributes
OneofthemostusefulandpowerfultechniqueswhenusingUnityistotakeadvantageofdependencyinjectionfortheparametersofclassconstructorsandmethods,andforthevaluesofproperties.Thisapproachallowsyoutoresolveandpopulatetheentirehierarchyofobjectsusedinyourapplicationbasedontyperegistrationsandmappingsdefinedinthecontainer,withthesubsequentadvantagesthisoffers.
Youcanspecifyconstructor,property,andmethodcallinjectioninformationinconfigurationorbyaddingregistrationstothecontaineratruntime.Youcanalsoapplyattributestomembersofyourclasses.Whenyouresolvetheseclassesthroughthecontainer,Unitywillgenerateinstancesofthedependentobjectsandwireupthetargetclasswiththeseinstances.
Unityperformsconstructorinjectionautomaticallyonresolvedclasses,choosingthemostcomplexconstructorandpopulatinganyparametersforwhichyoudonotprovidevalueswhenitconstructstheobject.YoucanalsospecifywhichconstructorUnityshouldusetoconstructtheobject.Formoreinformation,seeAnnotatingObjectsforConstructorInjection.
Propertyandmethodcallinjectiondonotoccurautomaticallyunlessyouhaveregisteredinjectiontypesinthecontaineratdesigntimeorruntime.Ifyouhavenotregisteredinjectiontypesinthecontainer,youcanaddattributestothemembersofyourresolvedclasstoforceinjectionofdependentobjectswhenthetargetclassisresolved.Formoreinformation,seeAnnotatingObjectsforProperty(Setter)InjectionandAnnotatingObjectsforMethodCallInjection.
Forinformationaboutregisteringinjectiontypesintheconfigurationatdesigntimeorruntime,seeConfiguringUnity.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1246: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1246.jpg)
MicrosoftEnterpriseLibrary5.0
AnnotatingObjectsforConstructorInjection
Unitysupportsautomaticdependencyinjectionforclassconstructors.YoucanusetheUnitycontainertogenerateinstancesofdependentobjectsandwireupthetargetclasswiththeseinstances.Thistopicexplainshowtouseboththeautomaticconstructorinjectionmechanismandanattributeappliedtotheconstructorofaclasstodefinethedependencyinjectionrequirementsofthatclass.Theattributecanalsospecifyparametersthattheconstructorwillpasstothedependentobjectthatthecontainergenerates.
ToperforminjectionofdependentclassesintoobjectsyoucreatethroughtheUnitycontainer,youcanusethefollowingtechniques:
SingleConstructorAutomaticInjection.Withthistechnique,youallowtheUnitycontainertosatisfyanyconstructordependenciesdefinedinparametersoftheconstructorautomatically.Youusethistechniquewhenthereisasingleconstructorinthetargetclass.SpecifyingNamedTypeMappings.Withthistechnique,youspecifynamedmappingsfordependenciesintheparametersofaclassconstructor.Namedmappingsallowyoutospecifymorethanonemappingforaninterfaceorbaseclass,orforatyperegistration.MultipleConstructorInjectionUsinganAttribute.Withthistechnique,youapplyattributestotheclassconstructor(s)thatspecifythedependencies.Youusethistechniquewhenthereismorethanoneconstructorinthetargetclass.
Constructorinjectionisaformofmandatoryinjectionofdependentobjects,aslongasdevelopersusetheUnitycontainertogeneratethetargetobject.ThedependentobjectinstanceisgeneratedwhentheUnitycontainercreatesaninstanceofthetargetclassusingtheconstructor.Formoreinformation,seeNotesonUsingConstructorInjection.
![Page 1247: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1247.jpg)
CopyCode
CopyCode
SingleConstructorAutomaticInjectionForautomaticconstructorinjection,yousimplyspecifyasparametersoftheconstructorthedependentobjecttypes.Youcanspecifytheconcretetype,orspecifyaninterfaceorbaseclassforwhichtheUnitycontainercontainsaregisteredmapping.
Touseautomaticsingle-constructorinjectiontocreatedependentobjects1. Defineaconstructorinthetargetclassthattakesasaparameterthe
concretetypeofthedependentclass.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingaconstructorthathasadependencyonaclassnamedMyDependentClass.C#
publicclassMyObject
{
publicMyObject(MyDependentClassmyInstance)
{
//workwiththedependentinstance
myInstance.SomeProperty="SomeValue";
//orassignittoaclass-levelvariable
}
}
VisualBasic
PublicClassMyObject
PublicSubNew(myInstanceAsMyDependentClass)
'workwiththedependentinstance
myInstance.SomeProperty="SomeValue"
'orassignittoaclass-levelvariable
EndSub
EndClass
2. Inyourrun-timecode,usetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillinstantiatethedependentconcreteclassandinjectitintothetarget
![Page 1248: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1248.jpg)
CopyCode
class.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontainingaconstructorthathasadependencyonaclassnamedMyDependentClass.C#
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
3. Alternatively,youcandefineatargetclassthatcontainsmorethanonedependencydefinedinconstructorparameters.TheUnitycontainerwillinstantiateandinjectaninstanceofeachone.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingaconstructorthathasdependenciesontwoclassesnamedDependentClassAandDependentClassB.C#
publicclassMyObject
{
publicMyObject(DependentClassAdepA,DependentClassBdepB)
{
//workwiththedependentinstances
depA.SomeClassAProperty="SomeValue";
depB.SomeClassBProperty="AnotherValue";
//orassignthemtoclass-levelvariables
}
}
VisualBasic
PublicClassMyObject
![Page 1249: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1249.jpg)
CopyCode
PublicSubNew(depAAsDependentClassA,depBAsDependentClassB)
'workwiththedependentinstance
depA.SomeClassAProperty="SomeValue"
depB.SomeClassBProperty="AnotherValue"
'orassignthemtoclass-levelvariables
EndSub
EndClass
4. Inyourrun-timecode,usetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillcreateaninstanceofeachofthedependentconcreteclassesandinjectthemintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontainingaconstructorthathasconstructordependencies.C#
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
5. Inadditiontousingconcretetypesasparametersofthetargetobjectconstructor,youcanuseinterfacesorbaseclasstypesandthenregistermappingsintheUnitycontainertotranslatethesetypesintothecorrectconcretetypes.Defineaconstructorinthetargetclassthattakesasparameterstheinterfaceorbasetypesofthedependentclass.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingaconstructorthathasadependencyonaclassthatimplementstheinterfacenamedIMyInterfaceandaclassthatinheritsfromMyBaseClass.C#
![Page 1250: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1250.jpg)
CopyCode
publicclassMyObject
{
publicMyObject(IMyInterfaceinterfaceObj,MyBaseClassbaseObj)
{
//workwiththeconcretedependentinstances
//orassignthemtoclass-levelvariables
}
}
VisualBasic
PublicClassMyObject
PublicSubNew(interfaceObjAsIMyInterface,baseObjAsMyBaseClass)
'workwiththedependentinstance
'orassignthemtoclass-levelvariables
EndSub
EndClass
6. Inyourrun-timecode,registerthemappingsyourequirefortheinterfaceandbaseclasstypes,andthenusetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillinstantiateaninstanceofeachofthemappedconcretetypesforthedependentclassesandinjectthemintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontainingaconstructorthathasadependencyonthetwoobjectsoftypeIMyInterfaceandMyBaseClass.C#
IUnityContaineruContainer=newUnityContainer()
.RegisterType<IMyInterface,FirstObject>()
.RegisterType<MyBaseClass,SecondObject>();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()_
![Page 1251: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1251.jpg)
.RegisterType(OfIMyInterface,FirstObject)()_
.RegisterType(OfMyBaseClass,SecondObject)()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
![Page 1252: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1252.jpg)
SpecifyingNamedTypeMappingsTheprecedingexampleshowshowyoucanresolvetypesforconstructorparametersusingthedefault(unnamed)mappingsinthecontainer.Ifyouregistermorethanonemappingforatype,youmustdifferentiatethembyusinganame.Inthiscase,youcanspecifywhichnamedmappingthecontainerwillusetoresolveeachconstructorparametertype.
Touseattributedconstructorinjectionwithnamedcontainertypemappings
1. Defineaconstructorinthetargetclassthattakesasaparametertheconcretetypeofthedependentclass,andapplyaDependencyattributetotheparameterthatspecifiesthenameoftheregisteredmappingtouse.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingaconstructorthathasadependencyonaserviceregisteredwiththenamemyDataService,andwhichimplementstheIMyServiceinterface.ItassumesthatthecontainercontainsamappingdefinedwiththenameDataServicebetweentheIMyServiceinterfaceandaconcreteimplementationofthisinterface.C#
publicclassMyObject
{
publicMyObject([Dependency("DataService")]IMyServicemyDataService)
{
//workwiththeservicehere
}
}
VisualBasic
PublicClassMyObject
PublicSubNew(<Dependency("DataService")>myDataServiceAsIMyService)
'workwiththeservicehere
EndSub
EndClass
![Page 1253: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1253.jpg)
CopyCode
2. Inyourrun-timecode,usetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillinstantiatethedependentconcreteclassdefinedinthemappingnamedDataServiceandinjectitintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassshownabove.C#
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
YoucanusetheDependencyattributeonmorethanoneconstructorparameter.Youcanalsouseitwhentheconstructordefinesmorethanoneparameterofthesametypetodifferentiatethemappingsandensurethattheappropriateconcretetypeisreturnedforeachparameter.
Note:Ifyouspecifyanamedmappingandthereisnomappingregisteredforthattypeandname,thecontainerwillraiseanexception.
![Page 1254: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1254.jpg)
CopyCode
CopyCode
MultipleConstructorInjectionUsinganAttributeWhenatargetclasscontainsmorethanoneconstructorwiththesamenumberofparameters,youmustapplytheInjectionConstructorattributetotheconstructorthattheUnitycontainerwillusetoindicatewhichconstructorthecontainershoulduse.Aswithautomaticconstructorinjection,youcanspecifytheconstructorparametersasaconcretetype,oryoucanspecifyaninterfaceorbaseclassforwhichtheUnitycontainercontainsaregisteredmapping.
Touseattributedconstructorinjectionwhenthereismorethanoneconstructor
1. ApplytheInjectionConstructorattributetotheconstructorinthetargetclassthatyouwantthecontainertouse.Inthesimplestcase,thetargetconstructortakesasaparametertheconcretetypeofthedependentclass.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingtwoconstructors,oneofwhichhasadependencyonaclassnamedMyDependentClassandhastheInjectionConstructorattributeapplied.C#
publicclassMyObject
{
publicMyObject(SomeOtherClassmyObjA)
{
...
}
[InjectionConstructor]
publicMyObject(MyDependentClassmyObjB)
{
...
}
}
VisualBasic
![Page 1255: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1255.jpg)
CopyCode
PublicClassMyObject
PublicSubNew(myObjAAsSomeOtherClass)
...
EndSub
<InjectionConstructor()>_
PublicSubNew(myObjBAsMyDependentClass)
...
EndSub
EndClass
2. Inyourrun-timecode,usetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillinstantiatethedependentconcreteclassdefinedintheattributedconstructorandinjectitintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontaininganattributedconstructorthathasadependencyonaclassnamedMyDependentClass.C#
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
3. Alternatively,youcandefineamultiple-constructortargetclassthatcontainsmorethanonedependencydefinedinthetargetconstructorparameters.TheUnitycontainerwillinstantiateandinjectaninstanceofeachone.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontaininganattributedconstructorthathasdependenciesontwoclasses,DependentClassAand
![Page 1256: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1256.jpg)
DependentClassB.C#
publicclassMyObject
{
publicMyObject(SomeClassAobjA,SomeClassBobjB)
{
...
}
[InjectionConstructor]
publicMyObject(DependentClassAdepA,DependentClassBdepB)
{
...
}
}
VisualBasic
PublicClassMyObject
PublicSubNew(objAAsSomeClassA,objBAsSomeClassB)
...
EndSub
<InjectionConstructor()>_
PublicSubNew(depAAsDependentClassA,depBAsDependentClassB)
...
EndSub
EndClass
4. Inyourrun-timecode,usetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillcreateaninstanceofeachofthedependentconcreteclassesdefinedinthe
![Page 1257: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1257.jpg)
CopyCode
attributedconstructorandinjectthemintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontainingaconstructorthathasconstructordependenciesC#
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
5. Inadditiontousingconcretetypesasparametersofthetargetobjectconstructor,youcanuseinterfacesorbaseclasstypes,andthenregistermappingsintheUnitycontainertotranslatethesetypesintothecorrectconcretetypes.Fordetails,seesteps5and6oftheprocedureSingleConstructorAutomaticInjection.
![Page 1258: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1258.jpg)
NotesonUsingConstructorInjection
![Page 1259: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1259.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1260: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1260.jpg)
CopyCode
MicrosoftEnterpriseLibrary5.0
AnnotatingObjectsforProperty(Setter)Injection
Unitysupportsdependencyinjectiontosetthevaluesorpropertiesthroughattributesappliedtomembersofthetargetclass.YoucanusetheUnitycontainertogenerateinstancesofdependentobjectsandwireupthetargetclasspropertieswiththeseinstances.Thistopicexplainshowtouseanattributethatisappliedtooneormorepropertydeclarationsofaclasstodefinethedependencyinjectionrequirementsofthatclass.Theattributecanspecifyparametersfortheattributetocontrolitsbehavior,suchasthenameofaregisteredmapping.
ToperformpropertyinjectionofdependentclassesintoobjectsyoucreatethroughtheUnitycontainer,youapplytheDependencyattributetothepropertydeclarationsofaclass.TheUnitycontainerwillcreateaninstanceofthedependentclasswithinthescopeofthetargetobject(theobjectyouspecifyinaResolvemethodcall)andassignthisdependentobjecttotheattributedpropertyofthetargetobject.
Propertyinjectionisaformofoptionalinjectionofdependentobjects,aslongasdevelopersusetheUnitycontainertogeneratethetargetobject.Thedependentobjectinstanceisgeneratedbeforethecontainerreturnsthetargetobject.Inaddition,unlikeconstructorinjection,youmustapplytheappropriateattributeinthetargetclasstoinitiatepropertyinjection.YoucanalsoperformpropertyinjectionofoptionaldependentclassesbyapplyingtheOptionalDependencyattribute.Thissimplymarksadependencyasoptional,whichmeansthatthecontainerwilltrytoresolveit,andreturnnulliftheresolutionfailsratherthanthrowanexception.Formoreinformation,seeNotesonUsingProperty(Setter)Injection.
Touseproperty(setter)injectiontocreatedependentobjectsforaclass1. DefineapropertyinthetargetclassandapplytheDependency
attributetoittoindicatethatthetypedefinedandexposedbythepropertyisadependencyoftheclass.ThefollowingcodedemonstratespropertyinjectionforaclassnamedMyObjectthatexposesasapropertyareferencetoaninstanceofanotherclassnamedSomeOtherObject(notdefinedinthiscode).C#
![Page 1261: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1261.jpg)
publicclassMyObject
{
privateSomeOtherObject_dependentObject;
[Dependency]
publicSomeOtherObjectDependentObject
{
get{return_dependentObject;}
set{_dependentObject=value;}
}
}
VisualBasic
PublicClassMyObject
Private_dependentObjectAsSomeOtherObject
<Dependency()>_
PublicPropertyDependentObject()AsSomeOtherObject
Get
Return_dependentObject
EndGet
Set(ByValvalueAsSomeOtherObject)
_dependentObject=value
EndSet
EndProperty
EndClass
2. Inyourrun-timecode,usetheResolvemethodofthecontainertocreateaninstanceofthetargetclass,andthenreferencethepropertycontainingthedependentobject.TheUnitycontainerwillinstantiatethedependentconcreteclassdefinedintheattributedpropertyandinjectitintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontaininganattributedpropertythathasadependencyonaclass
![Page 1262: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1262.jpg)
CopyCode
CopyCode
namedSomeOtherObjectandthenretrievethedependentobjectfromtheDependentObjectproperty.C#
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
//nowaccessthepropertycontainingthedependency
SomeOtherObjectdepObj=myInstance.DependentObject;
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
'nowaccessthepropertycontainingthedependency
DimdepObjAsSomeOtherObject=myInstance.DependentObject
3. Inadditiontousingconcretetypesforthedependenciesintargetobjectproperties,youcanuseinterfacesorbaseclasstypes,andthenregistermappingsintheUnitycontainertotranslatethesetypesintothecorrectconcretetypes.Defineapropertyinthetargetclassasaninterfaceorbasetype.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingpropertiesnamedInterfaceObjectandBaseObjectthathavedependenciesonaclassthatimplementstheinterfacenamedIMyInterfaceandonaclassthatinheritsfromMyBaseClass.C#
publicclassMyObject
{
privateIMyInterface_interfaceObj;
privateMyBaseClass_baseObj;
[Dependency]
![Page 1263: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1263.jpg)
CopyCode
publicIMyInterfaceInterfaceObject
{
get{return_interfaceObj;}
set{_interfaceObj=value;}
}
[Dependency]
publicMyBaseClassBaseObject
{
get{return_baseObj;}
set{_baseObj=value;}
}
}
VisualBasic
PublicClassMyObject
Private_interfaceObjAsIMyInterface
Private_baseObjAsMyBaseClass
<Dependency()>_
PublicPropertyInterfaceObject()AsIMyInterface
Get
Return_interfaceObj
EndGet
Set(ByValvalueAsIMyInterface)
_interfaceObj=value
EndSet
EndProperty
<Dependency()>_
PublicPropertyBaseObject()AsMyBaseClass
Get
Return_baseObj
EndGet
![Page 1264: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1264.jpg)
Set(ByValvalueAsMyBaseClass)
_baseObj=value
EndSet
EndProperty
EndClass
4. Inyourrun-timecode,registerthemappingsyourequirefortheinterfaceandbaseclasstypes,andthenusetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillcreateaninstanceofeachofthemappedconcretetypesforthedependentclassesandinjectthemintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontainingtwopropertiesthathavedependenciesonthetwoclassesnamedFirstObjectandSecondObject.C#
IUnityContaineruContainer=newUnityContainer()
.RegisterType<IMyInterface,FirstObject>()
.RegisterType<MyBaseClass,SecondObject>();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
//nowaccessthepropertiescontainingthedependencies
IMyInterfacedepObjA=myInstance.InterfaceObject;
MyBaseClassdepObjB=myInstance.BaseObject;
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()_
.RegisterType(OfIMyInterface,FirstObject)()_
.RegisterType(OfMyBaseClass,SecondObject)()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
'nowaccessthepropertiescontainingthedependencies
DimdepObjAAsIMyInterface=myInstance.InterfaceObject
DimdepObjBAsMyBaseClass=myInstance.BaseObject
![Page 1265: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1265.jpg)
CopyCode
CopyCode
5. Youcanregistermultiplenamedmappingswiththecontainerforeachdependencytype,ifrequired,andthenuseaparameteroftheDependencyattributetospecifythemappingyouwanttousetoresolvethedependentobjecttype.Forexample,thefollowingcodespecifiesthemappingnamesfortheKeypropertyoftheDependencyattributefortwopropertiesofthesametype(inthiscase,aninterface)intheclassMyObject.C#
publicclassMyObject
{
privateIMyInterface_objA,_objB;
[Dependency("MapTypeA")]
publicIMyInterfaceObjectA
{
get{return_objA;}
set{_objA=value;}
}
[Dependency("MapTypeB")]
publicIMyInterfaceObjectB
{
get{return_objB;}
set{_objB=value;}
}
}
VisualBasic
PublicClassMyObject
Private_objA,_objBAsIMyInterface
<Dependency("MapTypeA")>_
![Page 1266: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1266.jpg)
PublicPropertyObjectA()AsIMyInterface
Get
Return_objA
EndGet
Set(ByValvalueAsIMyInterface)
_objA=value
EndSet
EndProperty
<Dependency("MapTypeB")>_
PublicPropertyObjectB()AsIMyInterface
Get
Return_objB
EndGet
Set(ByValvalueAsIMyInterface)
_objB=value
EndSet
EndProperty
EndClass
6. Inyourrun-timecode,registerthenamed(non-default)mappingsyourequireforthetwoconcretetypesthatthepropertieswilldependon,andthenusetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillinstantiateaninstanceofeachofthemappedconcretetypesforthedependentclassesandinjectthemintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontainingtwopropertiesthathavedependenciesonthetwoclassesnamedFirstObjectandSecondObject.C#
IUnityContaineruContainer=newUnityContainer()
.RegisterType<IMyInterface,FirstObject>("MapTypeA")
.RegisterType<IMyInterface,SecondObject>("MapTypeB");
MyObjectmyInstance=uContainer.Resolve<MyObject>();
![Page 1267: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1267.jpg)
//nowaccessthepropertiescontainingthedependencies
IMyInterfacedepObjA=myInstance.ObjectA;
IMyInterfacedepObjB=myInstance.ObjectB;
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()_
.RegisterType(OfIMyInterface,FirstObject)("MapTypeA")_
.RegisterType(OfIMyInterface,SecondObject)("MapTypeB")
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
'nowaccessthepropertiescontainingthedependencies
DimdepObjAAsIMyInterface=myInstance.ObjectA
DimdepObjBAsIMyInterface=myInstance.ObjectB
![Page 1268: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1268.jpg)
UsingOptionalDependencies
![Page 1269: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1269.jpg)
NotesonUsingProperty(Setter)Injection
![Page 1270: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1270.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1271: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1271.jpg)
MicrosoftEnterpriseLibrary5.0
AnnotatingObjectsforMethodCallInjection
Unitysupportsdependencyinjectiontosetthevaluesofparametersofmethodsspecifiedthroughattributesappliedtomembersofthetargetclass.YoucanusetheUnitycontainertogenerateinstancesofdependentobjectsandwireupthetargetclassmethodparameterswiththeseinstances.Thistopicexplainshowtouseanattributethatisappliedtooneormoremethoddeclarationsofaclasstodefinethedependencyinjectionrequirementsofthatclass.
ToperforminjectionofdependentclassesintoobjectsyoucreatethroughtheUnitycontainer,youapplytheInjectionMethodattributetothemethoddeclarationsofaclass.TheUnitycontainerwillforcethetargetobject(theobjectyouspecifyinaResolvemethodcall)tocreateaninstanceofthedependentclassandthencallthetargetmethod.Ifrequired,yourcodeinthemethodcansavethisinstancebyassigningittoaclass-levelvariable.
MethodcallinjectionisaformofoptionalinjectionofdependentobjectsthatyoucanuseifyouusetheUnitycontainertogeneratethetargetobject.UnityinstantiatesdependentobjectsdefinedinparametersofmethodsthatcarrytheInjectionMethodattributewithinthescopeofthetargetobject.Thenitcallstheattributedmethodofthetargetobjectbeforereturningtheobjecttothecaller.YoumustapplytheInjectionMethodattributeinthetargetclasstoinitiatemethodcallinjection.Formoreinformation,seeNotesonUsingMethodCallInjection.
Tousemethodcallinjectiontocreatedependentobjectsforaclass1. DefineamethodinthetargetclassandapplytheInjectionMethod
attributetoittoindicatethatanytypesdefinedinparametersofthemethodaredependenciesoftheclass.Thefollowingcodedemonstratesthemostcommonscenario—savingthedependentobjectinstanceinaclass-levelvariable—foraclassnamedMyObjectthatexposesamethodnamedInitializethattakesasaparameterareferencetoaninstanceofanotherclassnamedSomeOtherObject(notdefinedinthiscode).C#
![Page 1272: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1272.jpg)
CopyCode
publicclassMyObject
{
privateSomeOtherObjectdependentObject;
[InjectionMethod]
publicvoidInitialize(SomeOtherObjectdep)
{
//assignthedependentobjecttoaclass-levelvariable
dependentObject=dep;
}
}
VisualBasic
PublicClassMyObject
PrivatedependentObjectAsSomeOtherObject
<InjectionMethod()>_
PublicSubInitialize(depAsSomeOtherObject)
'assignthedependentobjecttoaclass-levelvariable
dependentObject=dep
EndSub
EndClass
2. Inyourrun-timecode,usetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillinstantiatethedependentconcreteclassdefinedintheattributedmethod,injectitintothetargetclass,andexecutethemethod.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontaininganattributedmethodthathasadependencyonaclassnamedSomeOtherObject.C#
![Page 1273: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1273.jpg)
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
3. Inadditiontousingconcretetypesforthedependenciesintargetobjectmethods,youcanuseinterfacesorbaseclasstypesandthenregistermappingsintheUnitycontainertotranslatethesetypesintotheappropriateconcretetypes.Defineamethodinthetargetclassthattakesasparametersinterfacesorbasetypes.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingamethodnamedInitializethattakesasparametersanobjectnamedinterfaceObjthatimplementstheinterfacenamedIMyInterfaceandanobjectnamedbaseObjthatinheritsfromtheclassMyBaseClass.C#
publicclassMyObject
{
privateIMyInterfacedepObjectA;
privateMyBaseClassdepObjectB;
[InjectionMethod]
publicvoidInitialize(IMyInterfaceinterfaceObj,MyBaseClassbaseObj)
{
depObjectA=interfaceObj;
depObjectB=baseObj;
}
}
VisualBasic
PublicClassMyObject
![Page 1274: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1274.jpg)
CopyCode
PrivatedepObjectAAsIMyInterface
PrivatedepObjectBAsMyBaseClass
<InjectionMethod()>_
PublicSubInitialize(interfaceObjAsIMyInterface,baseObjAsMyBaseClass)
depObjectA=interfaceObj
depObjectB=baseObj
EndSub
EndClass
4. Inyourrun-timecode,registerthemappingsyourequirefortheinterfaceandbaseclasstypes,andthenusetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillinstantiateaninstanceofeachofthemappedconcretetypesforthedependentclasses,andinjectthemintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontaininganattributedmethodthathasdependenciesonthetwoclasses,FirstObjectandSecondObject.C#
IUnityContaineruContainer=newUnityContainer()
.RegisterType<IMyInterface,FirstObject>()
.RegisterType<MyBaseClass,SecondObject>();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()_
.RegisterType(OfIMyInterface,FirstObject)()_
.RegisterType(OfMyBaseClass,SecondObject)()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
![Page 1275: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1275.jpg)
SpecifyingNamedTypeMappingsTheprecedingexampleshowshowyoucanresolvetypesformethodparametersusingthedefault(unnamed)mappingsinthecontainer.Ifyouregistermorethanonemappingforatype,youmustdifferentiatethembyusinganame.Inthiscase,youcanspecifywhichnamedmappingthecontainerwillusetoresolvethemethodparametertypes.
Touseattributedmethodcallinjectionwithnamedcontainertypemappings
1. Defineamethodinthetargetclassthattakesasaparametertheconcretetypeofthedependentclass,andapplyaDependencyattributetotheparameterthatspecifiesthenameoftheregisteredmappingtouse.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingamethodnamedInitializethathasadependencyonaservicethatimplementstheIMyServiceinterface.ThecodeassumesthatthecontainercontainsamappingdefinedwiththenameDataServicebetweentheIMyServiceinterfaceandaconcreteimplementationofthatinterface.C#
publicclassMyObject
{
privateIMyServicemyDataService;
[InjectionMethod]
publicvoidInitialize([Dependency("DataService")]IMyServicetheService)
{
//assignthedependentobjecttoaclass-levelvariable
myDataService=theService;
}
}
VisualBasic
PublicClassMyObject
![Page 1276: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1276.jpg)
CopyCode
PrivatemyDataServiceAsIMyService
<InjectionMethod()>_
PublicSubInitialize(<Dependency("DataService")>theServiceAsIMyService)
'assignthedependentobjecttoaclass-levelvariable
myDataService=theService
EndSub
EndClass
2. Inyourrun-timecode,usetheResolvemethodofthecontainertocreateaninstanceofthetargetclass.TheUnitycontainerwillinstantiatethedependentconcreteclassdefinedintheattributedmethod,injectitintothetargetclass,andexecutethemethod.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampleclassshownabove.C#
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
Note:Ifyouspecifyanamedmappingandthereisnomappingregisteredforthattypeandname,thecontainerwillraiseanexception.
![Page 1277: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1277.jpg)
NotesonUsingMethodCallInjection
![Page 1278: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1278.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1279: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1279.jpg)
CopyCode
CopyCode
MicrosoftEnterpriseLibrary5.0
CircularReferenceswithDependencyInjection
Dependencyinjectionmechanismscarrytheriskofunintentionalcircularreferences,whicharenoteasytodetectorprevent.Thistopicdescribesthesituationswhereyoumayinadvertentlycausecircularreferencestooccur,resultinginastackoverflowandapplicationerror.Themostcommoncausesofcircularreferenceswithdependencyinjectionarethefollowing:
ObjectsgeneratedthroughconstructorinjectionthatreferenceeachotherintheirconstructorparametersObjectsgeneratedthroughconstructorinjectionwhereaninstanceofaclassispassedasaparametertoitsownconstructorObjectsgeneratedthroughmethodcallinjectionthatreferenceeachotherObjectsgeneratedthroughproperty(setter)injectionthatreferenceeachother
Forexample,thefollowingcodeshowstwoclassesthatreferenceeachotherintheirconstructors.C#
publicclassClass1
{
publicClass1(Class2test2)
{...}
}
publicclassClass2
{
publicClass2(Class1test1)
{...}
}
VisualBasic
PublicClassClass1
PublicSubNew(test2AsClass2)
![Page 1280: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1280.jpg)
...
EndSub
EndClass
PublicClassClass2
PublicSubNew(test1AsClass1)
...
EndSub
EndClass
Itistheresponsibilityofthedevelopertopreventthistypeoferrorbyensuringthatthemembersofclassestheyusewithdependencyinjectiondonotcontaincircularreferences.
Note:Youcoulduseconstructorinjectiontospecifyanyofaseriesofconstructorsormethodoverloads;however,youcouldinadvertentlycauseendlessrecursion.Toavoidtheendlessrecursion,specifywhichconstructortocallintheRegisterTypecall.
Unity'sdefaultbehavioristoresolvetheconstructorwiththemostparameters.Thiswouldcauseendlessrecursioninthefollowingexample.C#
container.RegisterType<IServiceProvider,ServiceContainer>();
varsp=container.Resolve<IServiceProvider>();
VisualBasic
container.RegisterType(OfIServiceProvider,ServiceContainer)()
Dimsp=container.Resolve(OfIServiceProvider)()
Toavoidtheendlessrecursion,specifywhichconstructortocallintheRegisterTypecall,asinthefollowingexample:
![Page 1281: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1281.jpg)
C#
container.RegisterType<IServiceProvider,ServiceContainer>(newInjectionConstructor());
VisualBasic
container.RegisterType(OfIServiceProvider,ServiceContainer)_
(NewInjectionConstructor())
Inthiscase,whencreatingtheservicecontainer,thezeroargumentconstructorisexplicitlyrequested.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1282: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1282.jpg)
MicrosoftEnterpriseLibrary5.0
InterceptionwithUnity
Unityinterceptionenablesyoutoeffectivelycapturecallstoobjectsandaddadditionalfunctionalitytothetargetobject.Interceptionisusefulwhenyouwanttomodifythebehaviorforindividualobjectsbutnottheentireclass,verymuchasyouwoulddowhenusingtheDecoratorpattern.Itprovidesaflexibleapproachforaddingnewbehaviorstoanobjectatruntime.
Thissectioncontainsthefollowingtopicsthatwillhelpyoutounderstandinterception:
AboutUnityInterception.ThissectionofthistopicdescribesthebasicprinciplesofinterceptioninUnity.ScenariosforInterception.ThistopicdescribescommonscenariosaddressedbyUnityinterception.BehaviorsforInterception.ThistopicdescribesbehaviorsyoumightimplementwiththeIInterceptionBehaviorinterfacetoconfigureacontainerthroughtheRegisterTypemethod.ConfiguringaContainerforInterception.ThistopicdescribeshowtoconfiguretheUnitycontainerforinterception.UnityInterceptionTechniques.ThistopicdescribesindetailthedesignofUnityinterception.UsingInterceptioninApplications.ThistopicdescribeshowyouuseUnityinterceptioninyourapplications.UsingInterceptionandPolicyInjection.ThistopicexplainshowpolicyinjectionthroughinterceptionworksinUnity,howyoucanusematchingrulestoselecttargetclassesandclassmembersforpolicyinjection,andhowyoucanusetheEnterpriseLibrarycallhandlerswithUnity.
![Page 1283: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1283.jpg)
AboutUnityInterceptionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1284: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1284.jpg)
MicrosoftEnterpriseLibrary5.0
ScenariosforInterception
Unityinterceptionaddressesthefollowingscenarios:Addingresponsibilitiestoindividualobjectsandnottheentireclassandavoidingastaticsolution,muchasinadecoratorpattern.Inamannersimilartothewayadecoratorforwardsrequeststotheobjectandenablesyoutoperformadditionalactionsbeforeorafterforwardingtherequest,interceptioninterceptsthecalltothetargetobjectanddynamicallyaddsbehaviorstoindividualobjectswithoutaffectinganyotherobjects.Thiscanbeusefulinmanagingcrosscuttingconcernsthataccesscommonfeaturessuchasloggingorvalidation.Toaugmentormodifythebehaviorfromexistingclassesthatyoucannotmodify,providedthattheyareinterceptablebytheavailableinterceptionmechanisms.Enablingthedeveloperandadministratortoconfigurethebehaviorofobjectsinanapplicationthroughconfigurationwhenusedinconjunctionwithadependencyinjection(DI)container,byaddingorremovingbehaviorsthatexecutecommontasksoraddcustomfeatures.Enablingthedeveloperandadministratortocapturecallstoobjectsandaddorremovebehaviorsthatexecutecommontasksoraddcustomfeaturesatruntime,butinthiscaseindependentofaDIcontainer.Minimizingtheworkrequiredandthecodethatthedevelopermustwritetoperformcommontaskswithinanapplication,suchaslogging,validation,authorization,andinstrumentation.Reducingdevelopmenttimeandcost,andminimizingbugsincomplexapplicationsthatusecommonandsharedtasksandservices.
![Page 1285: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1285.jpg)
BenefitsofUsingUnityInterception
![Page 1286: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1286.jpg)
LimitationsofUnityInterception
![Page 1288: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1288.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1289: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1289.jpg)
MicrosoftEnterpriseLibrary5.0
BehaviorsforInterception
Interceptionisbasedonabehaviororseriesofbehaviorsinthebehaviorspipelinethatdescribewhattodowhenanobjectisintercepted.Unityprovidesabuilt-indefaultpolicyinjectionbehaviortofacilitatetheimplementationofpolicyinjection.Thepolicyinjectionbehaviorattachesorinjectssomefunctionalitytospecificmethodsbyusingcallhandlersandmatchingrulesonaper-methodbasis.FormoreinformationonpolicyinjectionseeUsingInterceptionandPolicyInjection.
YoucanalsocreateyourowncustombehaviorsbyimplementingtheIInterceptionBehaviorinterface.Theinterceptionbehaviorsareaddedtoapipelineandarecalledforeachinvocationofthatpipeline.Youhavewidelatitudeinwhatfunctionalityyoudesignforyourbehavior.Somepracticalusesofbehaviorsincludeimplementingcustomtasksandbusinessrules,implementingINotifyPropertyChangedtosupportapropertychangeevent,toprovidesupportfortheErrorProvider/IDataErrorInfoapproachtovalidationinWindows®PresentationFoundation(WPF),andtoimplementaMockingframework.
Customtasksandbusinessrulesyoumightchosetoimplementwithindividualcustombehaviorswouldincludetaskssuchasvalidatingparametersorauthorizingusers.
WhenimplementingaWPFviewmodel,inordertogetthepropertychangeeventactionyoumustimplementINotifyPropertyChanged.Ratherthanimplementingthiseverytime,youcancreateabehaviorthataddsandimplementstheinterface.
Thereisnobuilt-insupportfortheErrorProvider/IDataErrorInfoapproachtovalidationinWPF;hencethereisnoErrorProvidercomponentinWPFeither.YoumustcreateanErrorProviderforuseinWPFapplications.TheDataGrid(1.1)andDataGridView(2.0)inWindowsFormsbothautomaticallydetectedthepresenceofthisinterfaceonobjectstheywereboundto,andshowedanyerrorswithoutanywork.TheWindowsFormsErrorProvidercouldbeusedtoautomaticallydisplayerrorsonanycontrolthatcamefromtheobjectsthey(andtheErrorProvider)wereboundto,allwithoutanyextracodebeingwritten.YoucanuseIDataErrorInfototakeadvantageofthevalidationworkinthe
![Page 1290: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1290.jpg)
.NETFramework.YoucanimplementIDataErrorInfoinaclassandbindtheclassconcreteobjecttotheDataGridViewcontrolthroughtheBindingsourceproperty.ThenusetheValidationApplicationBlocktovalidatetheclassobjectandstoretheresultsforeachproperty.
Implementingamockingframeworkthroughaninterceptionbehaviorcouldbeusefulincaseswherethecoderequiresaninterfacethathasnoimplementation.Thebehaviorcangiveyouamockupinterface.Youcoulduseamockingframeworktoimplementamockdatabase,mocklogger,ormockbuildercontext.
Thefollowingtopicsexplainordemonstrateinterceptionbehaviorsinmoredetail:
CustomInterceptionBehaviorsImplementIDataErrorInfoExample
![Page 1291: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1291.jpg)
CustomInterceptionBehaviors
![Page 1292: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1292.jpg)
ImplementINotifyPropertyChangedExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1293: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1293.jpg)
MicrosoftEnterpriseLibrary5.0
ConfiguringaContainerforInterception
Youcanuseinterceptionwithorwithoutadependencyinjection(DI)containersuchasUnity.UsingaDIcontainerrelievesyouoftheneedtomanuallycreateallthedependenciesandpassthemintothecorrectobjects.IfyouchoosetousetheUnityDIcontainer,youcanconfigurethecontainerbyusingaconfigurationfileoratruntimebyusingtheAPI.
InUnity,interceptionisjustanotherextensionpointinsteadofaself-containedpartoftheconfigurationfile,asinpreviousversions.PriortoUnity2.0whenyouspecifiedinterception,policyinjectionwasimplicitlyconfiguredbytheunderlyingcode.Wherethebehaviorofinterceptionwasimplicitbefore,itisexplicitnow;youspecifythatinterceptionistohappenandyouspecifywhatistohappenuponinterception.Interceptionbecomesjustonemorethingthatyoucandescribeabouthowanobjectisresolved.Unityversion2.0enablesyoutomodifyhowinterceptionhappensandhowtheobjectiscreated.
TherearetwoapproachesforsettingupUnityinterception:TheapproachintroducedinUnity2.0inwhichinterceptionisconfiguredasjustanotherextensionpointelementintheentryforacontainertype.Configureanextensionpointbyusingthe<sectionExtension>and<extension>tagsintheconfigurationfileorbyusingtheRegisterTypemethodatruntime.Thepre-Unity2.0approachusedinearlierversionsofUnityinwhichinterceptionisaself-containedpartofthecontainerconfiguredbyusingtheinterceptionextensionelements,<extensionConfig>and<interceptors>intheconfigurationfileorbyusingtheSetInterceptorFororSetDefaultInterceptorFormethodsontheinterceptioncontainerextension.Thisearlierstyleisstillavailableprimarilyforbackwardcompatibility.
Youcanuseaconfigurationfiletospecifyacontainer-createdbehaviorwithanylogicalconfiguration.Fordetailedinterceptionschemainformation,seeConfigurationFilesforInterception.
Thistopiccontainsthefollowingsectionstodescribehowtoconfigureacontainerforinterception:
![Page 1294: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1294.jpg)
AddingtheInterceptionExtensiontotheContainerConfiguringInterceptionofaTypeMoreInformation
![Page 1295: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1295.jpg)
AddingtheInterceptionExtensiontotheContainer
![Page 1296: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1296.jpg)
ConfiguringInterceptionofaType
![Page 1297: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1297.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1298: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1298.jpg)
MicrosoftEnterpriseLibrary5.0
UnityInterceptionTechniques
Inordertoperforminterception,Unitymustbeabletocapturetheoriginalcallandpassitthroughabehaviorspipelinetothetargetobject,thenpasstheresultbackthroughthebehaviorspipelinetotheoriginalcaller.Thetwocommonapproachestotheinterceptionprocessareinstanceinterceptionandtypeinterception,andUnityprovidestechniquesforboth.Instanceinterceptorsworkbycreatingaproxytotheinterceptedinstance.Typeinterceptorsworkbyderivinganewtypethatimplementsinterception.Theinstanceinterceptiontargetistheoriginal,non-interceptedobject,butwhenperformingtypeinterceptionthetargetisinterceptedandaderivedobjectused.
Note:Instanceinterceptionworksonlyoninstancemethods;itdoesnotworkforstaticmethodsorconstructorssincetheconstructorhasalreadyexecutedbythetimetheclientcodegetsbackaninterception-readyobject.Instanceinterceptioncanonlyinterceptpublicinstancemethods.Typeinterceptioncaninterceptpublicandprotectedmethods.
Thistopiccontainsthefollowingsectionsthatwillhelpyoutounderstandinterception:
InstanceInterceptionTypeInterceptionComparisonofInterceptionTechniquesSummaryofInterceptionApproaches
![Page 1299: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1299.jpg)
InstanceInterceptionInstanceinterceptionworkswithbothexistinginstancesofobjects,andwithnewinstancescreatedbyUnity.Thefollowingschematicshowsthebasicprocessofinstanceinterception.
WhentheapplicationresolvestheobjectthroughtheUnitycontainer,theUnityinterceptioncontainerextensionmanagestheprocess.Itobtainsaneworexistinginstanceoftheobjectfromthecontainer,andcreatesaproxytotheobject.Thenitcreatesthehandlerpipelineandconnectsittothetargetobjectbeforereturningareferencetotheproxy.Theclientthencallsmethodsandsetspropertiesontheproxyasthoughitwerethetargetobject.
Note:UnityinterceptioncanbeusedwithoutaUnityDIcontainerbyusingthestand-aloneAPIthroughthestaticInterceptclass.Formoreinformation,seeUsingInterceptioninApplications.
Thesecallspassthroughtheinterceptionbehaviors,executingthepreprocessingstageofeachone,withthefinalbehaviorinthechainpassingthecalltothetargetobject.Thereturnvaluefromthetargetobjectpassesbackthroughthebehaviorsinthereverseorder,executingthepost-processingstageofeachone.Thefirstbehaviorinthepipelinethenpassestheresultbacktothecaller.
![Page 1300: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1300.jpg)
Instanceinterceptionisthemostcommonandwidelyusedtechnique.ItcanbeusedwithobjectsthateitherimplementtheMarshalByRefObjectabstractclass,orimplementapublicinterfacethatdefinesallofthemethodstobeintercepted.Unityprovidesthetwointerceptors,TransparentProxyInterceptorandInterfaceInterceptor,thatsupportthesetwoscenarios.Formoredetails,seethetablesinComparisonofInterceptionTechniqueslaterinthistopic.
![Page 1301: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1301.jpg)
TypeInterceptionTypeinterceptionusesaderivedclassinsteadofaproxy.Asdescribedintheprevioussection,instanceinterceptionworksbycreatingaproxytothetargetobject.Typeinterception,ontheotherhand,morecloselyresemblesaspect-orientedprogramming(AOP)techniquescommoninJava-basedsystems.Typeinterceptionavoidsthepossibleperformancepenaltiesofusingaproxyobjectbydynamicallyderivinganewclassfromtheoriginalclass,andinsertingcallstothebehaviorsthatmakeupthepipeline.Thefollowingschematicshowsthebasicprocessoftypeinterception.
WhentheapplicationresolvestherequiredtypethroughtheUnitycontainer,theUnityinterceptioncontainerextensioncreatesthenewderivedtypeandpassesit,ratherthantheresolvedtype,backtothecaller.Becausethetypepassedtothecallerderivesfromtheoriginalclass,itcanbeusedinthesamewayastheoriginalclass.Thecallersimplycallstheobject,andthederivedclasswillpassthecallthroughthebehaviorsinthepipelinejustasisdonewhenusinginstanceinterception.
Note:
![Page 1302: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1302.jpg)
UnityinterceptioncanbeusedwithoutaUnityDIcontainerbyusingthestand-aloneAPIthroughthestaticInterceptclass.Formoreinformation,seeUsingInterceptioninApplications.
However,duetothenatureofthedynamictypegeneration,therearesomelimitationswiththisapproach.Itcanonlybeusedtointerceptpublicandprotectedvirtualmethods,andcannotbeusedwithexistingobjectinstances.Ingeneral,typeinterceptionismostsuitedtoscenarioswhereyoucreateobjectsespeciallytosupportinterceptionandallowfortheflexibilityanddecouplingprovidedbypolicyinjection,orwhenyouhavemappingsinyourcontainerforbaseclassesthatexposevirtualmethods.Formoredetails,seethetablesofcomparisonsinthefollowingtopicComparisonofInterceptionTechniques.
![Page 1303: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1303.jpg)
ComparisonofInterceptionTechniquesTheprevioussectionsdemonstratedhowitisimportanttochoosetheappropriateinterceptiontechniquebasedonyourrequirementsandthetypeofobjectyouwanttointercept.ThefollowingtableliststhethreeinterceptorclassesincludedinUnity,anddescribeswhenyoushoulduseeachtype.
Type Description Use
TransparentProxyInterceptor
Aninstanceinterceptor.Theproxyiscreatedbyusingthe.NETTransparentProxy/RealProxyinfrastructure.
WhenthetypetointerceptisaMarshalByRefObjectorwhenonlymethodsfromthetype'simplementedinterfacesneedtobeintercepted.
InterfaceInterceptor
Aninstanceinterceptor.Itcanproxyonlyoneinterfaceontheobject.Itusesdynamiccodegenerationtocreatetheproxyclass.
Whenresolvinganinterfacemappedtoatype.
VirtualMethodInterceptor
Atypeinterceptor.Itusesdynamiccodegenerationtocreateaderivedclassthatisinstantiatedinsteadoftheoriginalinterceptedclass,andtohookupthebehaviors.
Whenonlyvirtualmethodsneedtobeintercepted.
Selectionofaspecificinterceptordependsonyourspecificneeds,becauseeachonehasvarioustradeoffs.Thefollowingtablesummarizesthethreeinterceptorsandtheiradvantagesanddisadvantages.
Type Advantages Disadvantages
TransparentProxyInterceptor
Caninterceptallmethodsofthetargetobject(virtual,non-virtual,orinterface).
TheobjectmusteitherimplementaninterfaceorinheritfromSystem.MarshalByRefObjectIfthemarshalbyreference
![Page 1304: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1304.jpg)
objectisnotabaseclass,youcanonlyproxyinterfacemethods.TheTransparentProxyprocessismuchslowerthanaregularmethodcall.
InterfaceInterceptor
Allowsinterceptiononanyobjectthatimplementsthetargetinterface.ItismuchfasterthantheTransparentProxyInterceptor.
Itonlyinterceptsmethodsonasingleinterface.Itcannotcastaproxybacktothetargetobject'sclassortootherinterfacesonthetargetobject.
VirtualMethodInterceptor
CallsaremuchfasterthantheTransparentProxyInterceptor.
Interceptiononlyhappensonvirtualmethods.Youmustsetupinterceptionatobjectcreationtimeandcannotinterceptanexistingobject.
![Page 1305: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1305.jpg)
SummaryofInterceptionApproachesUnityprovidesinstanceandtypeinterceptionwithinterceptedobjectsforwhichyouhaveobtainedareferenceeitherthroughthecontainer,orbyusingthestand-aloneAPItoexplicitlyinterceptaknowninstance.Instanceinterceptorsuseaseparateproxyobjectbetweenyourcodeandyourtargetobject.Usinginterception,youmakeacallontheproxyobjectinsteadofdirectlycallingthetargetobject.Theproxyinvokesthevariousinterceptionbehaviors,andthenitforwardsthecalltothetargetobject.Differentimplementationsofinstanceinterceptorscanhavedifferentconstraints.Instanceinterceptorshavethefollowingcharacteristics:
Theycaninterceptobjectscreatedbythecontainer.Theycaninterceptobjectsnotcreatedbythecontainer.TheTransparentProxyInterceptorcaninterceptmorethanoneinterface,andmarshal-by-referenceobjects.TheInterfaceInterceptorcanonlybeusedtointerceptasingleinterface.
Typeinterceptorscreateanewtypethatinheritsfromthetargettype.Thisnewtypeistheninstantiatedinsteadoftheoriginaltypeyourequested.Thenewtypeoverridesallthevirtualmethodsontheoriginaltargettype.Typeinstanceinterceptorshavethefollowingcharacteristics:
Onlyoneobjectiscreated;thereisnoproxyobjectbetweenthecallerandthenewobject.Thenewobjecthasfulltypecompatibilitybecauseitisderivedfromthetargettype.Theyareabletointerceptobjectsonlyatcreation,andcannotinterceptexistinginstances.Theycanonlyinterceptvirtualpublicandprotectedmethods.
ThesystemthatUnityusestoautomaticallycreateaderivedtargetobject,oraproxyandbehaviorspipeline,issimilartotheaspect-orientedprogramming(AOP)approach.However,UnityisnotanAOPframeworkimplementationforthefollowingreasons:
Itusesinterceptiontoenableonlypreprocessingbehaviorsandpost-processingbehaviors.Itdoesnotinsertcodeintomethods,althoughitcancreatederived
![Page 1306: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1306.jpg)
classescontainingpolicypipelines.Itdoesnotprovideinterceptionforclassconstructors.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1307: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1307.jpg)
MicrosoftEnterpriseLibrary5.0
UsingInterceptioninApplications
ThistopicdescribeshowtouseUnityinterceptioninyourapplications.YoucanuseUnityinterceptionwithadependencyinjection(DI)containerorasastand-alonefeaturewithnoDIcontainer.
WhenyouuseaDIcontainer,thecontainerprovidesareferencetotheinterceptedobject.Whenthecontainerresolvesanobjectthatisconfiguredforinterception,theobjectisinterceptedasdefinedintheconfiguration.Whenperformingstand-aloneinterception,youmustalreadyhaveareferencetotheobjectyouwantintercepted.Youinvokethestand-aloneinterceptionAPIandexplicitlyintercepttheobject.Formoreinformationonusingcontainers,seeDependencyInjectionwithUnity.
Unityinterceptionrequiresaninterceptor,andacollectionofinterception
![Page 1308: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1308.jpg)
behaviorsthatcompriseapipeline.Interceptorsareusedwhenperforminginterceptionthroughthecontainerandthroughthestand-aloneAPI.Usingthecontainerresultsinaddinginterceptionobjectsthatarebeingresolved,whileusingthestand-aloneAPIenablesyoutoperformjustinterception.
Inbothcasesyoucanimplementadditionalinterfacesoninterceptedobjects.Youmustprovidetheinformationfortheadditionalinterfacesthatwillbeaddedforinterception.Usingadditionalinterfaceshassomelimitations.Youcannotaddopengenericinterfacesandyoucannotreimplementaninterfacethathasalreadybeenimplementedwithnonvirtualmethods.Additionalinterfacesaresupportedbyallthreetypesofinterceptors.Whenyouareperforminginterfaceinterception,youcanonlyinvokemethodsontheparticularinterfaceyouusedtointerceptandanyadditionalinterfacesthatyouhavespecified.Caststootherinterfacesimplementedbytheinterceptedobjectwillfail.
Thoughbehaviorsnormallycanhavebothpre-andpost-processingfunctionality,withanyadditionalinterfacesthebehaviorsmusthandletheprocessinginitsentirety.Therecannotbeanypost-processingbecausetheoriginalobjecthasnoimplementationfortheadditionalinterfaces’methods.AnycallstotheadditionalinterfacemethodshandledbythebehaviorswillresultinaNotImplementedExceptionbeingthrown.
Youcanalsointerceptabstractclasseswithabstractmethods,allowingthebehaviorspipelinetoprovidetheimplementationfortheseabstractmethods.Thisissimilartoaddinginterfacesinthatinbothcasesthereareundefinedmethodsforwhichanimplementationmustbeprovided,buttheyaredifferentmechanisms.AbstractclassinterceptiononlyworkswiththeVirtualMethodInterceptor.Youcanimplementabstractclasseswithabstractmethods.Ifyouinterceptatypethatalreadyimplementssomeinterfaces,bothvirtualmethodandtransparentproxyinterceptionallowforcastingtotheseinterfacesandinvokemethodsonthem,whichwillbeintercepted.Therecannotbeanypostprocessingbecausetheoriginalobjecthasnoimplementationfortheadditionalinterfaces’methods
Thistopiccontainsthefollowingsections:Stand-aloneUnityInterceptiondescribeshowtouseUnityinterceptionasastand-alonefeature.InterceptionBehaviorPipelinedescribeshowtoaddabehaviorandinterceptortoanewinterceptionbehaviorspipeline.
![Page 1309: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1309.jpg)
InterceptionwithaContainerdescribesinterceptionwithacontainer.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1310: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1310.jpg)
MicrosoftEnterpriseLibrary5.0
Stand-aloneUnityInterception
YoucanuseUnityinterceptionasastand-alonefeaturewithnodependencyinjectioncontainerbyusingtheInterceptclass.Aswithacontainer,interceptionasastand-alonefeatureenablesyoutoperforminstanceortypeinterception.TheInterceptclasscontainstheNewInstance,NewInstanceWithAdditionalInterfaces,ThroughProxy,andThroughProxyWithAdditionalInterfacesmethods,enablingyoutoperformeitherproxyorinstanceinterception.AndbothmethodsincludetheAdditionalInterfacesparameter,enablingyoutoimplementadditionalinterfacesonthetargetobject.ThiscorrespondstotheAdditionalInterfacefeaturewhenusinginterceptionwithacontainer.Note:
ThefirstparameteronIntercept.ThroughProxy,Intercept.ThroughProxyWithAdditionalInterfacesandIntercept.NewInstanceisthecorrespondinginterceptorwhensettingupinterceptionthroughthestand-aloneAPI.
TheAdditionalInterfacesparameterontheobjectenablesyoutoreceivemoremessagesandtoaugmentthesetofmethodstheobjectcanrespondto.
Thissectioncontainsthefollowingsectionsdescribingstand-aloneinterception:Stand-AloneInterceptionwithaProxydescribescreatingaproxytotheinterceptedinstance.Stand-AloneInterceptionwithaDerivedTypedescribesinterceptionbyusingaderivedtype.
![Page 1311: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1311.jpg)
Stand-AloneInterceptionwithaProxy
![Page 1312: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1312.jpg)
Stand-aloneInterceptionwithaDerivedTypeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1313: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1313.jpg)
CopyCode
CopyCode
CopyCode
MicrosoftEnterpriseLibrary5.0
InterceptionBehaviorPipeline
Youmustaddbehaviorstothebehaviorpipelinetousethem.Thepipelinemaintainsalistofinterceptionbehaviorsandmanagesthem,callingthemintheproperorderwiththecorrectinputs.
Thefollowingexampleaddsabehaviorandinterceptortoanewinterceptionbehaviorspipeline.
Firstcreateaninterceptionbehaviorspipeline.C#
privateInterceptionBehaviorPipelinepipeline=newInterceptionBehaviorPipeline();
VisualBasic
PrivatepipelineAsNewInterceptionBehaviorPipeline()
Thenaddaninterceptionbehaviortothepipeline.C#
pipeline.Add(interceptor);
VisualBasic
pipeline.Add(interceptor)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1314: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1314.jpg)
MicrosoftEnterpriseLibrary5.0
InterceptionwithaContainer
TheUnitycontainerextensionenablesyoutoconfigureacontainerforinterception.Youcanusethecontainerconfigurationtodeterminewhetheranobjectshouldbeintercepted,whichmechanismshouldbeusedtoperformtheinterception,andwhattodowhentheobjectisintercepted.ItalsoprovidesaconvenientsetofmethodsforconfiguringinjectionforMicrosoft.Practices.Unity.InterceptionExtension.RuleDrivenPolicyinstances.
FormoreinformationaboutconfiguringacontainerseeConfiguringaContainerforInterceptionandConfiguringUnity.
![Page 1315: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1315.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1316: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1316.jpg)
MicrosoftEnterpriseLibrary5.0
UsingInterceptionandPolicyInjection
PolicyinjectionbyacombinationofUnityandthepatterns&practicesEnterpriseLibraryusesasetofcallhandlersandtheequivalentcallhandlerattributesinconjunctionwiththeunderlyingUnityinterceptionmechanism.Interceptionenablesyoutoeffectivelycapturecallstoobjectsandprovideadditionalfunctionalitytothetargetobjectbyusingbehaviorsandcallhandlersinthepipelinetodefineandmanagetheresultsoftheinterception.InEnterpriseLibrary,policyinjectionisjustoneimplementationofaUnityinterceptionbehavior.ThePolicyInjectionBehaviorcapturescallstoobjectsyouresolvethroughthecontainer,andappliesapolicythatusescallhandlersandmatchingrulesinheritedfromUnitytodefineitspolicyinjectionbehavioronaper-methodbasis.
Typically,youwillusethistechniquetochangethebehaviorofexistingobjects,ortoimplementthemanagementofcrosscuttingconcernsthroughreusablehandlers.Youcanspecifyhowtomatchthetargetobjectusingawiderangeofmatchingrules,andconstructabehaviorwhichiseffectivelyapolicypipelinethatcontainsoneormorecallhandlers.
Callstotheinterceptedmethodsorpropertiesofthetargetobjectarepassedthroughthecallhandlersintheorderinwhichyouaddthemtothepipeline,andreturnedthroughtheminthereverseorder.Yourcallhandlerscanaccessthevaluesinthecall,changethesevalues,andcontrolexecutionofthecall.Forexample,thecallhandlersmightauthorizeusers,validateparametervalues,cachethereturnvalue,and,ifthelogicsodictates,shortcutexecutionsothatthetargetmethoddoesnotactuallyexecute.
Unityenablesyoutospecifyandcustomizeanyinterceptionbehaviorandalsoenablesyoutouseinterceptionwithorwithoutacontainer.Theearlierapproachtopolicyinjectionisstillsupported,butyoucanalsoprovidepolicyinjectionbyusinginterceptionbehaviors.
ForinformationonusingbehaviorsseeBehaviorsforInterception.
Forinformationonusinginterceptionwithoutacontainerseethe"Stand-AloneUnityInterception"sectionintheUsingInterceptioninApplicationstopic.
Thistopiccontainsthefollowingsectionsthatdescribeusingpolicyinjection
![Page 1317: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1317.jpg)
andcontainerswithinterception:ProcessFlowforInterceptionUsingPolicyInjectionUsingtheBuilt-InPolicyInjectionBehaviorInterceptionPoliciesMatchingRulesCallHandlersandPolicyInjectionMoreInformation
![Page 1318: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1318.jpg)
ProcessFlowforInterceptionUsingPolicyInjection
![Page 1319: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1319.jpg)
UsingtheBuilt-InPolicyInjectionBehavior
![Page 1320: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1320.jpg)
InterceptionPolicies
![Page 1321: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1321.jpg)
MatchingRules
![Page 1322: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1322.jpg)
CallHandlersandPolicyInjection
![Page 1323: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1323.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1324: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1324.jpg)
MicrosoftEnterpriseLibrary5.0
PolicyInjectionMatchingRules
UnityincludesmatchingruleimplementationsthatprovideawiderangeofcapabilitiesforselectingtheobjectsandtheirmemberstowhichUnitywilladdahandlerpipeline.Interceptionpoliciesusethematchingrulestodefinewhichmethodswillbeintercepted.
AmatchingruleisessentiallyapredicatethatUnitycheckseachtimeitinterceptsobjectcreation.IfallofthespecifiedmatchingrulesevaluatetoTrueforanyparticularinvocation,theapplicationblockwillcreateandaddthehandlerpipelineforthatpolicy.Ifanyoneofthematchingrulesdoesnotevaluatetotrue,Unitygeneratesaninstanceoftheoriginalobjectoraderivedobject,anddoesnotcreateaproxyorahandlerpipeline.
ThefollowingtableliststhematchingrulesprovidedwithUnity,andsummarizestheiruseandparameters.
Matchingrule Description
AssemblyMatchingRule
Selectsclassesinaspecifiedassembly.
CustomAttributeMatchingRule
Selectsclassesormembersthathaveanarbitraryattributeapplied.
MemberNameMatchingRule
Selectsclassmembersbasedonthemembername.
MethodSignatureMatchingRule
Selectsclassmethodsthathaveaspecificsignature.
NamespaceMatchingRule
Selectsclassesbasedonthenamespacename.
ParameterTypeMatchingRule
Selectsclassmembersbasedonthetypenameofaparameterforamemberofthetargetobject.
PropertyMatchingRule
Selectsclasspropertiesbynameandaccessortype.
ReturnType Selectsclassmembersthatreturnanobjectofthe
![Page 1325: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1325.jpg)
MatchingRule specifiedtype.
TagAttributeMatchingRule
SelectsclassmembersthatcarryaTagattributewiththespecifiedname.
TypeMatchingRule
Selectsclassesthatareofaspecifiedtype.
Thefollowingsectionsdescribethebuilt-inmatchingrulesindetail:TheAssemblyMatchingRuleTheCustomAttributeMatchingRuleTheMemberNameMatchingRuleTheMethodSignatureMatchingRuleTheNamespaceMatchingRuleTheParameterTypeMatchingRuleThePropertyMatchingRuleTheReturnTypeMatchingRuleTheTagAttributeMatchingRuleTheTypeMatchingRule
Youcanalsocreateandusecustommatchingrules.Formoreinformation,seeCreatingPolicyInjectionMatchingRules.Forinformationaboutusinginterception,seeUsingInterceptionandPolicyInjection.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1326: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1326.jpg)
MicrosoftEnterpriseLibrary5.0
TheAssemblyMatchingRule
Theassemblymatchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedontheassemblynameorbyspecifyingareferencetoanassembly.
![Page 1327: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1327.jpg)
BehavioroftheAssemblyMatchingRule
![Page 1328: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1328.jpg)
CreatinganAssemblyMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1329: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1329.jpg)
MicrosoftEnterpriseLibrary5.0
TheCustomAttributeMatchingRule
Thecustomattributematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonacustomattributetypethatisappliedtoclassmembers.
![Page 1330: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1330.jpg)
BehavioroftheCustomAttributeMatchingRule
![Page 1331: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1331.jpg)
CreatingaCustomAttributeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1332: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1332.jpg)
MicrosoftEnterpriseLibrary5.0
TheMemberNameMatchingRule
Themembernamematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthenameoftheclassmembers(methodsorproperties),andallowsyoutousewildcardcharactersforthemembername.
![Page 1333: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1333.jpg)
BehavioroftheMemberNameMatchingRule
![Page 1334: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1334.jpg)
CreatingaMemberNameMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1335: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1335.jpg)
MicrosoftEnterpriseLibrary5.0
TheMethodSignatureMatchingRule
Themethodsignaturematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthenameandsignature(thelistofparametertypes)ofitsmembers.Thisruleallowstheuseofwildcardcharactersforthemembernames.
![Page 1336: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1336.jpg)
BehavioroftheMethodSignatureMatchingRule
![Page 1337: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1337.jpg)
CreatingaMethodSignatureMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1338: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1338.jpg)
MicrosoftEnterpriseLibrary5.0
TheNamespaceMatchingRule
Thenamespacematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedontheirnamespace,usingwildcardcharactersforthechildnamespacenamesbutnotfortherootnamespacename.
![Page 1339: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1339.jpg)
BehavioroftheNamespaceMatchingRule
![Page 1340: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1340.jpg)
CreatingaNamespaceMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1341: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1341.jpg)
MicrosoftEnterpriseLibrary5.0
TheParameterTypeMatchingRule
Theparametertypematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthetypenameofaparameterforamemberofthetargetobject.
![Page 1342: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1342.jpg)
BehavioroftheParameterTypeMatchingRule
![Page 1343: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1343.jpg)
CreatingaParameterTypeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1344: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1344.jpg)
MicrosoftEnterpriseLibrary5.0
ThePropertyMatchingRule
Thepropertymatchingruleallowsdevelopers,operators,andadministratorstoselectindividualpropertiesofthetargetclassesbasedontheirname,includingusingwildcardcharacters,andthecombinationofaccessorstheyimplement.
![Page 1345: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1345.jpg)
BehaviorofthePropertyMatchingRule
![Page 1346: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1346.jpg)
CreatingaPropertyMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1347: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1347.jpg)
MicrosoftEnterpriseLibrary5.0
TheReturnTypeMatchingRule
Thereturntypematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthetypeorthetypenameofthereturnvalue,usingwildcardcharactersifrequired.
![Page 1348: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1348.jpg)
BehavioroftheReturnTypeMatchingRule
![Page 1349: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1349.jpg)
CreatingaReturnTypeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1350: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1350.jpg)
CopyCode
CopyCode
MicrosoftEnterpriseLibrary5.0
TheTagAttributeMatchingRule
Thetagattributematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthenameofanattributeoftypeTagthatisappliedtoaclass,ortomembers(methodsorproperties)withinaclass.Forexample,thefollowingcodeshowsaclasswithtwotaggedmembers.C#
publicclassAnnotatedWithTags
{
[Tag("MyTagName")]
publicvoidTaggedMethod(stringparameter1)
{
...methodimplementationhere...
}
[Tag("AnotherTagName")]
publicstringTaggedProperty
{
...propertyimplementationhere...
}
}
VisualBasic
PublicClassAnnotatedWithTags
<Tag("MyTagName")>_
PublicSubTaggedMethod(parameter1AsString)
...methodimplementationhere...
EndSub
<Tag("AnotherTagName")>_
PublicPropertyTaggedPropertyAsString
![Page 1351: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1351.jpg)
CopyCode
CopyCode
...propertyimplementationhere...
EndProperty
EndClass
Thefollowingcodeshowsataggedclass.C#
[Tag("MyClassTagName")]
publicclassAnnotatedWithTagOnClass
{
...classimplementationhere...
}
VisualBasic
<Tag("MyClassTagName")>_
PublicClassAnnotatedWithTagOnClass
...classimplementationhere...
EndClass
![Page 1352: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1352.jpg)
BehavioroftheTagAttributeMatchingRule
![Page 1353: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1353.jpg)
CreatingaTagAttributeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1354: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1354.jpg)
MicrosoftEnterpriseLibrary5.0
TheTypeMatchingRule
Thetypematchingruleallowsdevelopers,operators,andadministratorstospecifythetargetclassusingthenamespaceandclassnameofthetargettype.
![Page 1355: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1355.jpg)
BehavioroftheTypeMatchingRule
![Page 1356: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1356.jpg)
CreatingaTypeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1357: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1357.jpg)
MicrosoftEnterpriseLibrary5.0
Attribute-DrivenPolicies
Acommonscenariowhenusinganypolicyinjectionframeworkistherequirementtospecifypoliciesforclassesandtheirmembersusingattributesdirectlyappliedtotheappropriateclassesandmembers.Unityinterceptionsupportsthistechnique—itactivelydiscoversclassesandmemberswithattributesthatdefinecallhandlersandappliestheappropriatepolicies.
Developersspecifyhandlersforclassesandtheirmembers(methodsandproperties)usingcallhandlerattributes.Eachattributeautomaticallyinstantiatestheappropriatecallhandler,andappliesthevaluesoftheattributeparameterstothepropertiesofthecallhandler.Usingdirectlyappliedattributeshasthefollowingadvantages:
DeveloperscanensurethatUnityaddshandlersthatarespecificallyrequiredinallcircumstancesandwhichshouldneverberemovedfromthehandlerpipeline.Developerscanfixthesettingsorvaluesofspecificparametersonclassesandclassmembers—forexample,bydefiningthatspecificparametervaluesmustalwaysbegreaterthanzeroorthatloggingwillalwaysoccurforspecificmethods.Developerscanpreventtheapplicationofahandlerpipelinetospecificmethodsandproperties,ortowholeclasses,usingtheApplyNoPoliciesAttributeattribute.
However,applyingpoliciesthroughattributesapplieddirectlytomembersofthetargetclassesmeansthatdevelopers,administrators,andoperatorscannolongercontrolthebehaviorofinterceptionwithoutchangingthesourcecodeandrecompilingthesolution.Inaddition,usingtheApplyNoPoliciesAttributeattributemaycauseunexpectedbehaviorfordevelopers,administrators,andoperators,whomayattempttoaddpoliciestoanapplicationwithoutbeingawareoftheappliedattributes.
![Page 1358: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1358.jpg)
PolicyandHandlerPrecedencewithAttributes
![Page 1359: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1359.jpg)
ExampleofanAttribute-DrivenPolicyToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1360: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1360.jpg)
MicrosoftEnterpriseLibrary5.0
EnterpriseLibraryCallHandlers
Thepatterns&practicesEnterpriseLibraryincludesasetofcallhandlersandtheequivalentcallhandlerattributesdesignedforusewiththeUnityPolicyInjectionBehavior.ThissectiondiscussessomeofthecommonscenariosforusingthePolicyInjectionApplicationBlockcallhandlers.Itexaminesthefollowingcommonscenarioswheretheblockcansimplifyandaccelerateapplicationdevelopment:
LoggingMethodInvocationandPropertyAccessHandlingExceptionsinaStructuredMannerValidatingParameterValuesAuthorizingMethodandPropertyRequestsMeasuringTargetMethodPerformance
![Page 1361: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1361.jpg)
LoggingMethodInvocationandPropertyAccess
![Page 1362: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1362.jpg)
HandlingExceptionsinaStructuredManner
![Page 1363: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1363.jpg)
ValidatingParameterValues
![Page 1364: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1364.jpg)
AuthorizingMethodandPropertyRequests
![Page 1365: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1365.jpg)
MeasuringTargetMethodPerformance
![Page 1366: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1366.jpg)
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1367: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1367.jpg)
MicrosoftEnterpriseLibrary5.0
TheAuthorizationHandler
Theauthorizationhandlerprovidesthecapabilitytocheckthatthecurrentuser(thesecurityprincipalforthecurrentthread)hastherequisitepermissiontoaccesstheselectedobjectmethodorproperty.ThishandlerusestheSecurityApplicationBlockandtakesadvantageofthefeaturesthatitexposes.
Theauthorizationhandlerappliesthesecuritycheckbeforeinvocationoftheselectedmethodorsettingoftheselectedpropertyofthetargetobject.Ifthecurrentuserdoesnothavepermissiontoaccessthemethodorpropertyaccessor,theauthorizationhandlerabortsexecutionduringthepreprocessingstageanddoesnotinvokethetargetmethodorsetthetargetproperty.ItalsogeneratesanUnauthorizedAccessExceptionandpackagesitintothemessagepassedbacktotheprevioushandlerinthepipeline.
Note:ThiscallhandlerisimplementedintheMicrosoft.Practices.EnterpriseLibrary.Security.PolicyInjectionnamespaceoftheSecurityApplicationBlockintheMicrosoft.Practices.EnterpriseLibrary.Security.dllassembly.
![Page 1368: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1368.jpg)
BehavioroftheAuthorizationHandler
![Page 1369: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1369.jpg)
CreatingInstancesoftheAuthorizationHandler
![Page 1370: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1370.jpg)
UsingtheAuthorizationHandlerAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1371: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1371.jpg)
MicrosoftEnterpriseLibrary5.0
TheExceptionHandlingHandler
Theexceptionhandlinghandlerprovidesthecapabilitytomanageandprocessexceptionsinastandardway.ThishandlerusestheExceptionHandlingApplicationBlock,takingadvantageofthewiderangeofoptionsthatitsupports.
Theexceptionhandlerappliesafterinvocationoftheselectedmethodoraccesstotheselectedpropertyofthetargetobject.Ifthemethodorpropertyaccessorraisesanexception,theexceptionhandlinghandlerwillinvokeanamedexceptionhandlingpolicydefinedwithintheExceptionHandlingApplicationBlock.Thispolicymayignoretheexception,returntheoriginalexception,orreplaceitwithanewexception.Theexceptionhandlinghandlerthenpackagestheexception(iftheExceptionHandlingApplicationBlockreturnsone)intothemessagepassedbacktotheprevioushandlerinthechain.
Eachinstanceoftheexceptionhandlinghandlermaintainsitsownhierarchyofexceptionpoliciesandanydependentobjects.WhenusingthelogginghandlerwiththeExceptionHandlingApplicationBlock,eachexceptionhandlinghandlerinstancewillcontainitsownLogWriterinstanceandsetofTraceListeners.IftheLoggingApplicationBlockisconfiguredtouseaflatfiletracelistenerorarollingflatfiletracelistener,youmayseemultiplelogfileswithGUIDsintheirfilenamesbecausemultipleinstancesofthetracelistenersarenotabletowritetotheconfiguredlogfileatthesametime.
Note:ThiscallhandlerisimplementedintheMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling.PolicyInjectionnamespaceoftheExceptionHandlingApplicationBlockintheMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling.dllassembly.
![Page 1372: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1372.jpg)
BehavioroftheExceptionHandlingHandler
![Page 1373: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1373.jpg)
CreatingInstancesoftheExceptionHandlingHandler
![Page 1374: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1374.jpg)
UsingtheExceptionHandlingHandlerAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1375: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1375.jpg)
MicrosoftEnterpriseLibrary5.0
TheLoggingHandler
Thelogginghandlerprovidesthecapabilitytowritelogmessagesandtracemessagesastheclientcodeinvokestheselectedmethodoraccessestheselectedpropertyofthetargetobject.ThishandlerusestheLoggingApplicationBlock,takingadvantageofthewiderangeoflogtypes,formatting,andtracingfeaturesthatitprovides.
Thelogginghandlerappliesbothbeforeandaftertheinvocationoftheselectedmethodoraccessingtheselectedpropertyofthetargetobject,dependingonsettingsintheapplicationconfiguration.
Note:ThiscallhandlerisimplementedinMicrosoft.Practices.EnterpriseLibrary.Logging.PolicyInjectionnamespaceoftheLoggingApplicationBlockintheassemblyMicrosoft.Practices.EnterpriseLibrary.Logging.dll.
ThelogginghandlerwillinitializetheLoggingApplicationBlockusingthesameconfigurationsourceasusedtocreatethelogginghandler.Bydefault,thiswillbethedefaultconfigurationsource.Itispossibletospecifyanalternativeconfigurationsourceifyouinstantiatethelogginghandleryourselfusingcode.Ifyoudothis,youshouldcreatetheconfigurationsourceonceandusethesameinstanceeachtimeyoucreatealogginghandlertopreventperformanceissuesandmemoryleaks.
Note:TheEnterpriseLibrary5.0ConfigurationtooldoesnotsupportEnvironmentalOverridesforthelogginghandlerCategories.Thismeansyouwillnotbeabletousetheconfigurationtoolsatdesigntimetocustomizetherun-timesettingsofyourlogginghandlerCategoriesconfigurationtosuitaparticularenvironmentsuchasatestorinstrumentationenvironment.
![Page 1376: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1376.jpg)
BehavioroftheLoggingHandler
![Page 1377: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1377.jpg)
CreatingInstancesoftheLoggingHandler
![Page 1378: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1378.jpg)
UsingtheLoggingHandlerAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1379: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1379.jpg)
MicrosoftEnterpriseLibrary5.0
ThePerformanceCounterHandler
Theperformancecounterhandlerincrementsaspecificcountereachtimeitexecutesinresponsetoinvocationoftheselectedmethodorsettingoftheselectedproperty.ThishandlerusestheinstrumentationfeaturesthatarepartoftheEnterpriseLibraryCore.
Theperformancecounterhandlerappliesbothbeforeandafterinvocationoftheselectedmethodoraccesstotheselectedpropertyofthetargetobject.Thehandlercanincrementdifferenttypesofcountersandincrementmorethanonecountereachtime(suchasasingleinstanceandatotalcounter).
Note:ThiscallhandlerisimplementedintheMicrosoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlersnamespaceoftheMicrosoft.Practices.EnterpriseLibrary.PolicyInjection.dllassembly.
![Page 1380: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1380.jpg)
InstallingandRemovingPerformanceCounters
![Page 1381: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1381.jpg)
BehaviorofthePerformanceCounterHandler
![Page 1382: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1382.jpg)
CreatingInstancesofthePerformanceCounterHandler
![Page 1383: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1383.jpg)
UsingthePerformanceCounterHandlerAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1384: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1384.jpg)
MicrosoftEnterpriseLibrary5.0
TheValidationHandler
Thevalidationhandlerprovidesthecapabilitytotestwhetherthevalueprovidedfortheselectedproperty,orthevaluesspecifiedfortheparametersoftheselectedmethod,arevalidagainstspecificrules.ThishandlerusestheValidationApplicationBlock,takingadvantageofthewiderangeofcapabilitiesthatitoffers.
Thevalidationhandlerappliesthevalidationbeforeinvokingthemethodorsettingthepropertyofthetargetobject.Ifvalidationfails,thevalidationhandlerabortsexecutionofthepreprocessinghandlerpipeline,doesnotinvokethemethodorsettheproperty,andraisesanArgumentValidationException.
Note:ThiscallhandlerisimplementedinMicrosoft.Practices.EnterpriseLibrary.Validation.PolicyInjectionnamespaceoftheValidationApplicationBlock,intheassemblyMicrosoft.Practices.EnterpriseLibrary.Validation.dll.
![Page 1385: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1385.jpg)
BehavioroftheValidationHandler
![Page 1386: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1386.jpg)
CreatingInstancesoftheValidationHandler
![Page 1387: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1387.jpg)
UsingtheValidationHandlerAttribute
![Page 1388: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1388.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1389: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1389.jpg)
MicrosoftEnterpriseLibrary5.0
DesignofUnity
Thistopicdescribesthedesigngoals,thearchitecture,andthedesignhighlightsofUnity.YoudonothavetounderstandthedesigntouseUnity;however,thistopicwillhelpyoutounderstandhowitworksandhowitinteractswiththeunderlyingObjectBuildersubsystem.
![Page 1390: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1390.jpg)
DesignGoals
![Page 1391: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1391.jpg)
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1392: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1392.jpg)
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingUnity
Ifrequired,youcanextendandmodifyUnitytobettersuityourownrequirements.YoucanextendUnitybydoingthefollowing:
CreatingLifetimeManagersthatcontrolhowandwhenthecontainerwilldisposeofinstancesofobjectsitresolves.CreatingandUsingContainerExtensionsthatcanchangethebehaviorofthecontainer,theinstancegenerationmechanism,andthedependencyinjectionandinterceptionfeatures.CreatingPolicyInjectionMatchingRulesthatprovidesalternativetechniquesforselectingclassesandclassmemberstowhichUnitywillattachahandlerpipeline.CreatingInterceptionPolicyInjectionCallHandlersthatperformthetask-specificprocessingyourequireformethodinvocationsandpropertyaccessors.CreatingInterceptionHandlerAttributesthatcauseUnitytoaddbuilt-inorcustomcallhandlerstothehandlerpipeline.Ifyoucreateacustomhandler,youmayalsowanttocreateacustomattributethatdeveloperscanusetoapplyyourhandlerbyaddingtheattributedirectlytoclassesorclassmemberswithinthesourcecodeofanapplication.CreatingInterceptionBehaviorsthatdescribewhattodowhenanobjectisintercepted.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1393: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1393.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingLifetimeManagers
Unitysupportsseveralapproachesforregisteringclasses,interfaces,andinstancesofexistingobjects.YoucanusetheRegisterTypeandRegisterInstancemethodstoregisterobjectinstancesatruntime,orspecifythemappingsandregistrationsatdesigntimeinconfiguration.YoucanalsospecifyalifetimemanagerwithalloftheseapproachesthatwillcontrolhowUnityresolvesinstancesofthespecifiedtypesandhowitholdsreferencestotheseinstances.Thebuilt-inlifetimemanagersallowyoutospecifyobjectsassingletons,withweakreferences,orasper-threadinstances.Formoredetails,seeUnderstandingLifetimeManagers.
YoucancreatecustomLifetimeManagerclassesifyourequireadditionalfunctionalitynotavailableinthedefaultlifetimemanagers.DocumentationtohelpyoudothisisavailablefromtheUnityCommunityWebsiteonCodePlex.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1394: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1394.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingandUsingContainerExtensions
YoucancreateyourowncustomUnitycontainerextensions,orusecontainerextensionscreatedbythirdpartieswithUnity.Unityusesdefaultcontainerextensionstoimplementitsownfunctionality.Forexample,theinterceptionmechanismprovidedbyUnityisimplementedasacontainerextension.
DocumentationtohelpyouunderstandObjectBuilder,andthestepsrequiredtocreatecustomcontainerextensions,isavailablefromtheUnityCommunityWebsiteonCodePlex.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1395: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1395.jpg)
CopyCode
CopyCode
MicrosoftEnterpriseLibrary5.0
CreatingPolicyInjectionMatchingRules
UnitydefinesaninterfacenamedIMatchingRule,whichallclassesthatimplementmatchingrulesmustimplement.ThisinterfacedeclaresasinglemethodnamedMatchesthattakesaMethodBaseinstanceandreturnsaBooleanvalue.C#
publicinterfaceIMatchingRule
{
boolMatches(MethodBasemember);
}
VisualBasic
PublicInterfaceIMatchingRule
FunctionMatches(ByValmemberAsMethodBase)AsBoolean
EndInterface
Insideaconcreteimplementationofthisinterface,acustommatchingruleclasscanaccessdetailsofthecurrentmember(methodorproperty)ofthetargetobjectanddeterminewhetherUnityshouldaddahandlerpipelinetothismember.TheMatchesmethodshouldreturnTrueifthecurrentmembermatchestherequirementsofthismatchingrule;ifthecurrentmemberdoesnotmatchtherequirementsofthismatchingrule,itshouldreturnFalse.
Note:Rememberthattheremaybeseveralmatchingrulesdefinedforapolicy,andeveryonemustreturnTruewhenUnitycallstheirMatchesmethodinorderforUnitytoaddthehandlerpipelinetothetargetclassmember.
![Page 1396: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1396.jpg)
Example:TheTagAttributeMatchingRuleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1397: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1397.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingInterceptionPolicyInjectionCallHandlers
Tocreateacallhandlerforpolicyinjection,youmustunderstandthewaythatUnitypassescallsthroughthepolicypipeline.Thistopicexplainshowthepipelineexecutescallhandlers,andhowitcanblockorabortexecutionwhenanerroroccurs,orondemand(suchaswhenavalidationhandlerdetectsavalidationerrororanauthorizationhandlerdetectsanunauthorizeduser).Thistopiccontainsthefollowingsections:
TheICallHandlerInterfaceandPipelineExecutionOutlineImplementationofaCallHandlerExceptionsandAbortedPipelineExecution
![Page 1398: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1398.jpg)
TheICallHandlerInterfaceandPipelineExecution
![Page 1399: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1399.jpg)
OutlineImplementationofaCallHandler
![Page 1400: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1400.jpg)
ExceptionsandAbortedPipelineExecutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1401: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1401.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingInterceptionHandlerAttributes
Handlerattributesallowdeveloperstoapplyhandlerstoclassesandclassmembersdirectly,withoutconfiguringthemintheapplicationconfigurationfile.Developerscreatingcustomhandlersmaywanttoprovideanattributefortheirhandlers.Tobuildacustomhandlerattribute,youcreateaclassthatderivesfromtheHandlerAttributebaseclassshownhere.C#
publicabstractclassHandlerAttribute:Attribute
{
///Derivedclassesimplementthismethod.Whencalled,itcreatesa
///newcallhandlerasspecifiedintheattributeconfiguration.
///Theparameter"container"specifiestheIUnityContainer
///tousewhencreatinghandlers,ifnecessary.
///returnsanewcallhandlerobject.
publicabstractICallHandlerCreateHandler(IUnityContainercontainer);
privateintexecutionorder;
///<summary>
///Getsorsetstheorderinwhichthehandlerwillbeexecuted.
///</summary>
publicintOrder
{
get{returnthis.executionorder;}
set{this.order=value;}
}
}
VisualBasic
PublicMustInheritClassHandlerAttribute:InheritsAttribute
'''Derivedclassesimplementthismethod.Whencalled,itcreatesa
'''newcallhandlerasspecifiedintheattributeconfiguration.
![Page 1402: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1402.jpg)
'''TheparametercontainerspecifiestheIUnityContainer
'''tousewhencreatinghandlers,ifnecessary.
'''Returnsanewcallhandlerobject.
PublicMustOverrideFunctionCreateHandler(containerAsIUnityContainer)AsICallHandler
PrivateexecutionorderAsInteger
'''<summary>
'''Getsorsetstheorderinwhichthehandlerwillbeexecuted.
'''</summary>
PublicPropertyOrderAsInteger
Get
ReturnMe.executionorder
EndGet
Set
Me.order=value
EndSet
EndProperty
EndClass
Inyourcustomattributeclass,youmustimplementoneormoreconstructorsthatacceptvaluesfromtheattribute,and/orimplementnamedpropertiesthatthedevelopercanusetosetthepropertiesoftheclass.ThenyousimplyoverridetheCreateHandlerabstractmethoddeclaredwithinthebaseclasstocreateandreturntherequiredhandlerclassasanICallHandlerinstance.
![Page 1403: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1403.jpg)
ExampleCallHandlerAttributeAsanexample,youcouldcreateacallhandlerattributeforacallhandlersimilartothatdescribedinthetopicCreatingInterceptionPolicyInjectionCallHandlersthatpreventsinvocationofbusinessprocessesonweekenddays.Inthiscase,assumethatthehandlerhasapropertynamedSaturdayOKthatallowsyoutosetittoallowcallstooccuronaSaturday.Thecallhandlerhastwoconstructors:onethattakesaparameterthatsetsthevalueoftheSaturdayOKpropertytothespecifiedvalue(trueorfalse),andonethattakesnoparametersandsetsthedefaultvalue(false)fortheSaturdayOKproperty.ThefollowingcodeshowsanimplementationoftheWeekdayOnlyCallHandlerAttribute.C#
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Property|AttributeTargets.Method)]
publicclassWeekdayOnlyCallHandlerAttribute:HandlerAttribute
{
privateboolallowSaturday;
publicWeekdayOnlyCallHandlerAttribute()
{
allowSaturday=false;
}
publicWeekdayOnlyCallHandlerAttribute(boolSaturdayOK)
{
allowSaturday=SaturdayOK;
}
publicoverrideICallHandlerCreateHandler(IUnityContainerignored)
{
returnnewWeekdayOnlyCallHandler(allowSaturday,Order);
}
}
VisualBasic
![Page 1404: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1404.jpg)
<AttributeUsage(AttributeTargets.ClassOrAttributeTargets.PropertyOrAttributeTargets.Method)>_
PublicClassWeekdayOnlyCallHandlerAttribute:InheritsHandlerAttribute
PrivateallowSaturdayAsBoolean
PublicSubNew()
allowSaturday=False
EndSub
PublicSubNew(SaturdayOKAsBoolean)
allowSaturday=SaturdayOK
EndSub
PublicOverridesFunctionCreateHandler(ignoredAsIUnityContainer)AsICallHandler
ReturnNewWeekdayOnlyCallHandler(allowSaturday,Order)
EndFunction
EndClass
NoticetheAttributeUsageattributethatspecifieswheredeveloperscanapplythenewcustomattribute(onaclass,aproperty,oramethod),and—inthiscase—theprovisionoftwoconstructors.Thefirst(default)constructorusesthedefaultvalue(false),whilethesecondacceptsavaluefortheSaturdayOKproperty.TheCreateHandlermethodoverrideinstantiatestheWeekdayOnlyCallHandlerclasswiththeappropriatevaluesandreturnsthisasanICallHandlerreference.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1405: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1405.jpg)
MicrosoftEnterpriseLibrary5.0
CreatingInterceptionBehaviors
UnityusestheInterceptorclasstospecifyhowinterceptionhappens,andtheInterceptionBehaviorclasstodescribewhattodowhenanobjectisintercepted.Unityinterceptionutilizesabehaviorpipelinetoforthebehaviors.TheInterceptionBehaviorPipelinemaintainsalistofinterceptionbehaviorsandmanagesthem,callingthemintheproperorderwiththecorrectinputs.
ForinformationonthedetailsaboutinterceptionbehaviorsseeInterceptionwithUnityandBehaviorsforInterception.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1406: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1406.jpg)
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
WhenyouuseUnityinyourapplications,youmustdeploytherequiredassemblieswithyourapplicationorinstalltheassembliesonthetargetcomputerintheglobalassemblycache(GAC).YoumustincludetheassemblynamedMicrosoft.Practices.Unity.dll.Ifyouareusinginterception,youwillalsorequiretheassemblynamedMicrosoft.Practices.Unity.Interception.dll.
YoucandeployanapplicationthatusesUnityinoneoftwoconfigurations:AsprivateassembliesintheapplicationfolderhierarchyAssharedassembliesinanyfilesystemlocationorintheglobalassemblycache
ForadviceonusingUnitywithapplicationsthatruninpartialtrustmodes,seeUsingUnityinPartialTrustEnvironments.
ForadviceonupdatingexistingversionsofUnityassemblies,seeUpdatingtheUnityAssemblies.
WhenyoucompiletheinstalledversionofUnitysourcecode,theassembliesproducedwillnotbestrongnamed.Asaresult,theycannotbeinstalledintheglobalassemblycache,norwilltheyhavetheotherbenefitsassociatedwithstrong-namedassemblies.TolearnhowtostrongnameUnityassemblies,seeStrongNamingtheUnityAssemblies.
Note:Unitythrows(andhandlesinternally)LockSynchronizationexceptions.LockSynchronizationexceptionsmaybeobservedinthedebuggeroutputbuttheyarehandledinternallyandnoactionisrequired.
![Page 1407: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1407.jpg)
UsingXCopy
![Page 1409: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1409.jpg)
VersioningToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1410: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1410.jpg)
MicrosoftEnterpriseLibrary5.0
UsingUnityinPartialTrustEnvironments
Unityusesdynamicallygeneratedmethodstoperforminjection,andthe.NETFrameworksecuritymodelimposessomesecuritylimitationsthatyoushouldbeawareofifyouwanttouseUnityinapplicationsthatwillruninlessthanfulltrustenvironments.ThelimitationwhenusingUnityinapartialtrustenvironmentisthatyoucannotregisterandusemappingsusingtheRegisterTypemethodswherethetargetclassisinternal(C#),Friend(VisualBasic.NET),private(C#),orPrivate(VisualBasic.NET).
FormoreinformationaboutsecurityissueswhenusingdynamicallygeneratedMicrosoftintermediatelanguage(MSIL)code,seeSecurityIssuesinReflectionEmitfor.NET3.5andSecurityIssuesinReflectionEmitfor.NET2.0.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1411: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1411.jpg)
MicrosoftEnterpriseLibrary5.0
UpdatingtheUnityAssemblies
IfanupgradedversionofUnitybecomesavailable,youcaninstallthenewversionandhaveallapplicationsusetheupdatedassembly.However,ifthenewversionintroducescompatibilityproblemsforcertainapplications,youcaninstallthenewversionintheglobalassemblycacheandconfiguresomeapplicationstousetheupdatedversion,whileotherscontinuetousetheearlierversion.
![Page 1412: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1412.jpg)
UpdatingPrivateAssemblies
![Page 1413: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1413.jpg)
UpdatingSharedAssembliesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1414: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1414.jpg)
MicrosoftEnterpriseLibrary5.0
StrongNamingtheUnityAssemblies
IfyoubuildUnityfromthesourcecode,youmaydecidetoapplystrongnamingtotheassemblies.Astrongnameconsistsoftheassembly'sidentity—thesimpletextname,versionnumber,andcultureinformation(ifprovided)—plusapublickeyandadigitalsignature.Thestrongnameisgeneratedfromanassemblyfile(thefilethatcontainstheassemblymanifest,whichinturncontainsthenamesandhashesofallthefilesthatmakeuptheassembly),usingthecorrespondingprivatekey.Signinganassemblywithastrongnameensuresthatitsnameisgloballyunique.Assemblieswiththesamestrongnameareexpectedtobeidentical.
Forexample,ifyouintendtoshareUnityassembliesamongseveralapplications,youcaninstallthemintotheglobalassemblycache.Eachassemblyintheglobalassemblycachemusthaveagloballyuniquename.Youcanuseastrongnametoensurethis.Evenifyouonlyusetheassemblieswithinasingleapplication,youcanstrongnametheassembliestoensurethatyourapplicationusesthecorrectversionoftheassemblies.
Strongnamessatisfythefollowingrequirements:Strongnamesguaranteenameuniquenessbyrelyingonuniquekeypairs.Noonecangeneratethesameassemblynamethatyoucanbecauseanassemblygeneratedwithoneprivatekeyhasadifferentnamethananassemblygeneratedwithanotherprivatekey.Strongnamesprotecttheversionlineageofanassembly.Astrongnamecanensurethatnoonecanproduceasubsequentversionofyourassembly.Userscanbesurethataversionoftheassemblytheyareloadingcomesfromthesamepublisherthatcreatedtheversionoriginallyprovidedwiththeapplication.Strongnamesprovideastrongintegritycheck.Passingthe.NETFrameworksecuritychecksguaranteesthatthecontentsoftheassemblyhavenotbeenchangedsinceitwasbuilt.However,notethatstrongnamesthemselvesdonotimplyaleveloftrustsuchasthelevelprovidedby,forexample,adigitalsignatureandsupportingcertificate.
Forinformationaboutdeployingassembliesintotheglobalassemblycache,seeWorkingwithAssembliesandtheGlobalAssemblyCache.
![Page 1415: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1415.jpg)
UsingVisualStudiotoStrongNametheUnityAssembliesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1416: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1416.jpg)
MicrosoftEnterpriseLibrary5.0
UnityQuickStarts
TheinstructionsinthisQuickStarttopicaredirectedattheSilverlightsolution.Thoughtherearemanysimilarities,someinstructionsinthistopic,suchasreferencestoProgram.csorProgram.vb,donotapplytotheSilverlightproject.ThefollowingQuickStartapplicationsdemonstratesomeofthekeyfeaturesofUnity:
Walkthrough:TheUnityStopLightQuickStart.ThisQuickStartdemonstratesdependencyinjectiontechniques.ThisistheonlyQuickStartprojectintheSilverlightsolution.Walkthrough:TheUnityEventBrokerExtensionQuickStart.ThisQuickStartprovidesanexampleextensionfortheUnitycontainer.TheSilverlightsolutiondoesnoincludetheEventBrokerQuickStart.
Note:UnityQuickStartsareonlyavailableifyouinstallthestandaloneUnityMSI.TheUnityMSIisavailableatpatterns&practices-UnityonCodePlex.
![Page 1417: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1417.jpg)
BuildingtheQuickStartsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1418: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1418.jpg)
MicrosoftEnterpriseLibrary5.0
Walkthrough:TheUnityStopLightQuickStart
TheStopLightQuickStartdemonstratesthewaysthatyoucanuseUnityandtheUnitycontainerinyourapplications.TheuserinterfaceisasimpleWindowsFormsapplicationthatdisplaysthethreecolorsofastoplightortrafficlight—itshowsred,yellow,andgreen,inturn,forspecifiedperiods.Youcanconfigurethedisplayperiodsforeachcolor.Thefollowingillustrationshowstheuserinterface.
TheStopLightQuickStartdemonstratesthefollowingfeaturesofUnity:RegisteringmappingsfortypeswiththecontainerImplementingtheModelViewPresenterpatternbyinjectingapresenterintotheuserinterfaceInjectingabusinesscomponentintoobjectsusingproperty(setter)injectionImplementingaconfigurablepluggablearchitecture
ThefollowingdiagramshowstheclassesandarchitectureoftheStopLightQuickStartapplication.
![Page 1419: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1419.jpg)
![Page 1420: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1420.jpg)
RegisteringMappingsforTypeswiththeContainer
![Page 1421: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1421.jpg)
ImplementingtheModel-View-PresenterPattern
![Page 1422: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1422.jpg)
InjectingaBusinessComponentusingProperty(Setter)Injection
![Page 1423: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1423.jpg)
ImplementingaConfigurablePluggableArchitectureToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
![Page 1424: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1424.jpg)
MicrosoftEnterpriseLibrary5.0
Walkthrough:TheUnityEventBrokerExtensionQuickStart
TheEventBrokerExtensionQuickStartdemonstrateshowyoucanextendtheUnitycontainerbyaddingacustomextension.TheQuickStartimplementsaneventbrokerforthecontainerasacontainerextensionanddemonstratesthenewextensionusingtheStopLightapplicationdiscussedinWalkthrough:TheUnityStopLightQuickStart.
TheEventBrokerExtensionQuickStartcontainsfiveprojects:SimpleEventBroker.Thisprojectimplementsasimplepublishandsubscribemechanismthatsupportsmultipleeventpublishersandmultiplesubscribers.EventBrokerExtension.Thisprojectimplementsthecustomcontainerextensionthatallowsapplicationstopublishandsubscribetoeventsusingattributesorexplicitlyusingcode.StopLight.ThisprojectisbasicallythesameasthatdescribedintheUnityStopLightQuickStart,butitusesthecustomcontainerextensiontomanagethepublishingof,andsubscriptionto,twoeventswithintheapplication.Tests.EventBrokerExtension.AtestfixturefortheEventBrokerExtension.Tests.SimpleEventBroker.AtestfixturefortheSimpleEventBroker.
Forinformationabouthowyoucancreateandusecustomcontainerextensions,seeCreatingandUsingContainerExtensions.
ThefollowingdiagramshowstheclassesandarchitectureoftheEventBrokerExtensionQuickStart.
![Page 1425: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1425.jpg)
IfyoucomparethisdiagramtothestructureoftheStopLightQuickStartshowninWalkthrough:TheUnityStopLightQuickStart,youcanseethattheEventBrokerExtensionQuickStarthasthefollowingadditionalfeatures:
TheProgramclass,whichregistersthetypemappingsinthecontainerandcallstheResolvemethodtoinstantiatethemainStopLightform,alsoaddstheSimpleEventBrokerExtensiontothecontainer.TheSimpleEventBrokerExtension,whichinheritsfromtheUnityContainerExtensionbaseclass,createsaninstanceoftheEventBrokerclassthatimplementsthepublishandsubscribepatternfordistributedevents.TheEventBrokerclasscreatesaninstanceofthePublishedEventclassthatprovidesthefacilitiesformaintainingalistofeventsubscriptionsandraisingeventstoregisteredsubscribers.TheStopLightPresenter,StopLightSchedule,andRealTimeTimerclassesincludeattributesthatregistereventpublicationsandsubscriptionswiththeSimpleEventBrokerExtensionclass.
TheEventBrokerExtensionQuickStartdemonstratesthefollowingfeaturesofUnityandthecustomcontainerextensionmechanism:
![Page 1426: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1426.jpg)
CreatingthecustomUnitycontainerextensionAddinganextensiontotheUnitycontaineratruntimeUsingtheexampleEventBrokerExtension
![Page 1427: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1427.jpg)
CreatingaCustomUnityContainerExtension
![Page 1428: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1428.jpg)
AddinganExtensiontotheUnityContaineratRunTime
![Page 1429: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement](https://reader034.vdocuments.mx/reader034/viewer/2022042411/5f294e76dc3f0f712c43cfee/html5/thumbnails/1429.jpg)
UsingtheExampleEventBrokerExtensionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.