1429
Microsoft Enterprise Library 5.0 Welcome to Enterprise Library Welcome to Enterprise Library. The following sections of this guidance describe the ways that you can use Enterprise Library and the individual application blocks in your applications. The sections are: What Is Enterprise Library? About This Release of Enterprise Library Developing Applications with Enterprise Library Design of Enterprise Library The Caching Application Block

Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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 13: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UsingaNon-defaultConfigurationStoreSharingtheSameConfigurationbetweenMultipleApplicationsManagingandEnforcingConfigurationforMultipleApplicationsSharingConfigurationSectionsacrossMultipleApplicationsApplyingaCommonConfigurationStructureforApplicationsManagingConfigurationinDifferentDeploymentEnvironments

Youcanalsochangethecontentsofaconfigurationfileprogrammatically,whichisusefulwhenworkingwithsharedconfigurationstoredasdiskfiles.Formoreinformation,seeUpdatingSharedConfigurationSettingsProgrammatically.Forlinkstorelatedtopicsandmoredetailsofhowtheconfigurationsystemworks,seeMoreInformationattheendofthistopic.

Page 54: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

UsingaNon-defaultConfigurationStore

Page 55: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5. ClicktheConfigurationSourcespropertyexpanderchevrontoopenthepropertiespaneforthesection.SettheParentSourcepropertytotheconfigurationsourcewhosesettingsyouwanttoinherit.

6. ClickSaveorSaveAsontheFilemenutosaveyourconfiguration.

Settingsintheinheritedconfigurationsourcewillapplytoyourapplicationunlessyouoverridethembyconfiguringthesamesettinginyourlocalconfiguration.Forinformationabouthowsettingsareinheritedandmerged,seeMergeRulesforInheritedConfiguration.

Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,pleasesendemailto

Page 72: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

AddingaManageableConfigurationSource

Page 83: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

.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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

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

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

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

{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

TheUnityResolveMethod

Page 173: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

ResolvingInstancesofEnterpriseLibraryTypes

Page 174: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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 179: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

UsingXCopy

Page 184: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

MicrosoftEnterpriseLibrary5.0

PartialTrustEnvironments

ApplicationsthatuseversionsoftheEnterpriseLibrarypriortoversion3.0requireenoughpermissionssothattheonlysecurityleveltheycanuseisfulltrust.WithlaterversionsofEnterpriseLibrary,includingthisversion,youcanrunapplicationsunderpartialtrust.AcommonexampleisanASP.NETapplicationthatrunsinahostedenvironment.Typically,thesetypesofapplicationsrequireonlyenoughpermissionstorunundermediumtrust.DependingontheEnterpriseLibraryfeaturesthatyourapplicationuses,youmayneedtograntadditionalpermissionsbeyondthosegrantedbyadefaultpartial-trustpolicy.

Thistopiccontainsthefollowingsections:OverviewofPartialTrustEnterpriseLibraryandPartialTrustEnterpriseLibraryCodeAccessSecurityandtheSecurityTransparentAttribute

Page 197: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 223: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

MicrosoftEnterpriseLibrary5.0

TheDependencyInjectionModel

ThistopicdescribesthemechanismusedbyEnterpriseLibrarytocreateandmanagethelifetimeofobjectswithinthecoreandtheapplicationblocks.EnterpriseLibraryusesadependencyinjectionmechanismtocreateandmanagethelifetimeofalltheEnterpriseLibraryobjectsitcreates.Dependingonthestyleofyourapplication,itmayusethesamedependencyinjectioncontainerthatEnterpriseLibraryuses.Thistopiccontainsthefollowingsections:

ApplicationandContainerInitializationUsinganAlternativeDependencyInjectionContainerMoreInformation

TolearnhowtousetheUnitydependencyinjectionapproachwhenwritingapplicationcode,seeUsingEnterpriseLibraryinApplications.

Page 257: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

ApplicationandContainerInitialization

Page 258: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

GroupPolicyTemplateStructureGeneralSettingsfortheApplicationBlocksExceptionstotheGeneralTemplateStructureApplyingGroupPolicySettingsLimitationsofGroupPolicySupport

Page 269: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

GroupPolicyTemplateStructure

Page 270: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

BenefitsoftheCachingApplicationBlock

Page 288: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

AlternativestoUsingtheCachingApplicationBlock

Page 289: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 307: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

UsingtheNullBackingStore

Page 308: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

UsingtheIsolatedStorageBackingStore

Page 309: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

ModifyingtheKeyManagementCode

Page 427: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

BenefitsoftheDataAccessApplicationBlock

Page 445: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

.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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

WritingCodetoUsetheDatabaseClasses

Page 473: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

'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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

{

//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

="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

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

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

CreatingAccessorsthroughDependencyInjection

Page 511: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

AccessingandIteratingtheResultsSet

Page 512: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

QueryingtheResultsSetUsingLINQ

Page 513: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 589: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

MicrosoftEnterpriseLibrary5.0

SendinganExceptiontotheExceptionHandlingApplicationBlock

InteractionbetweenapplicationcodeandtheExceptionHandlingApplicationBlockoccurswhentheapplicationcodecatchesanexceptionandsendsittotheblocktobehandled.Applicationdevelopersdonothavetoknowhowexceptionswillbehandledbecausetheyhavetospecifyonlythenameoftherelevantexceptionpolicy.

Therearethreemainscenariosinwhichyoumayneedtohandleexceptions.Themostcommonisthefirstofthese,butthistopicexplainshowyoucanusetheblocktoimplementallthreescenarios.Thescenariosare:

HandlingAllExceptionsinaCatchSectionHandlingSpecificExceptionsinaCatchSectionExecutingCodeBeforeorAfterHandlinganException

Page 633: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 690: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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&amp;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

</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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

categoryFiltersChildElement

Page 767: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

listenersChildElement(allEvents)

Page 775: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

EachinstanceoftheLoggingApplicationBlockusesaninstanceofthemessagequeuingtracelistener(theMsmqTraceListenerclass)tosendthelogentriestoasingledestinationqueue.ThedistributorservicepollsthequeueandusesanotherinstanceoftheLoggingApplicationBlocktodirectthelogentriestothepropertracelisteners.Notethatthedistributorservicecanrunonaremotecomputer.Thefollowingsectionsdescribeinstallingandusingthedistributorservice:

InstallingtheDistributorServiceStartingtheDistributorServiceUnderstandingtheserviceNameAttribute

Page 781: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 845: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

AuthorizationRuleProvider

Page 861: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

validationElement

Page 924: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

EncryptedDataElement

Page 925: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[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

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

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 1039: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

MicrosoftEnterpriseLibrary5.0

AboutThisReleaseofUnity

ThissectioncontainsthefollowingtopicsthatwillhelpyoutounderstandthisreleaseofUnityandhelpyouunderstandhowtouseitalongsideearlierversionsormigrateyourapplicationstothisversion.Thissectionincludesthefollowingtopics:

ChangesinThisReleaseTargetAudienceandSystemRequirementsMigrationandSide-by-SideExecutionRelatedpatterns&practicesLinksCopyrightandTermsofUse

Page 1076: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

HowtoUseThisGuidance

Page 1078: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

LoadingConfigurationFileInformationintoaContainer

Page 1101: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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 1111: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

The<unity>ConfigurationSection

Page 1112: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 1187: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

DefaultInterceptorforaType

Page 1188: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

.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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

//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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

.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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

//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

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

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

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

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

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

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

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

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

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

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

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

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

...

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

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

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

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

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

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

LimitationsofUnityInterception

Page 1287: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

AlternativestoUsingUnityInterception

Page 1288: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

.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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

'''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

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

<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

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

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

UsingXCopy

Page 1408: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

UsingtheGlobalAssemblyCache

Page 1409: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

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
Page 1420: Microsoft Enterprise Library 5 - Documentation & Helpacross different layers of their applications. Unity Dependency Injection and Interception. Developers can use this to implement

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

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

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

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

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

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

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

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

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

UsingtheExampleEventBrokerExtensionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].

Copyright©2010byMicrosoftCorporation.Allrightsreserved.