MicrosoftEnterpriseLibrary5.0
WelcometoEnterpriseLibrary
WelcometoEnterpriseLibrary.ThefollowingsectionsofthisguidancedescribethewaysthatyoucanuseEnterpriseLibraryandtheindividualapplicationblocksinyourapplications.Thesectionsare:
WhatIsEnterpriseLibrary?AboutThisReleaseofEnterpriseLibraryDevelopingApplicationswithEnterpriseLibraryDesignofEnterpriseLibraryTheCachingApplicationBlock
TheCryptographyApplicationBlockTheDataAccessApplicationBlockTheExceptionHandlingApplicationBlockTheLoggingApplicationBlockThePolicyInjectionApplicationBlockTheSecurityApplicationBlockTheValidationApplicationBlockUnityDependencyInjectionandInterception
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhatIsEnterpriseLibrary?
EnterpriseLibraryconsistsofacollectionofapplicationblocksandcoreinfrastructure.Allofthesearereusablesoftwarecomponentsdesignedtoassistdeveloperswithcommonenterprisedevelopmentchallenges.
EnterpriseLibraryalsoprovidesmanyhighlyconfigurablefeaturesthatmakeitmucheasiertomanagerepetitivetasks,knownascrosscuttingconcerns,whichoccurinmanyplacesinyourapplications.Theseincludetaskssuchaslogging,validation,caching,exceptionmanagement,andmore.Inaddition,thedependencyinjectioncontaineritprovidescanhelptosimplifyanddecoupleyourdesigns,makethemmoretestableandunderstandable,andhelpyoutoproducemoreefficientdesignsandimplementationsofallkindsofapplications.
ThreeSimpleStepsforUsingEnterpriseLibrary
BenefitsofEnterpriseLibrary
GoalsforEnterpriseLibraryToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
AboutThisReleaseofEnterpriseLibrary
ThissectioncontainsthefollowingtopicsthatwillhelpyoutounderstandthisreleaseofEnterpriseLibraryandhowyouuseitalongsideearlierversionsormigrateyourapplicationstothisversion.Thissectionincludesthefollowingtopics:
ChangesinThisReleaseTargetAudienceandSystemRequirementsContentsofEnterpriseLibraryMigrationandSide-by-SideExecutionRelatedpatterns&practicesLinksCopyrightandTermsofUse
HowtoUseThisGuidanceToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
IntegrationofUnityandObjectBuilder
ChangesThatAffectAllApplicationBlocks
ChangestotheConfigurationTools
ChangestotheCachingApplicationBlock
ChangestotheCryptographyApplicationBlock
ChangestotheDataAccessApplicationBlock
ChangestotheExceptionHandlingApplicationBlock
ChangestotheLoggingApplicationBlock
ChangestothePolicyInjectionApplicationBlock
ChangestotheSecurityApplicationBlock
ChangestotheValidationApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TargetAudienceandSystemRequirements
Thisguidanceisintendedforsoftwarearchitectsandsoftwaredevelopers.Togetthegreatestbenefitfromthisguidance,youshouldhaveanunderstandingofthefollowingtechnologies:
MicrosoftVisualC#®orMicrosoftVisualBasic®.NETMicrosoft.NETFramework
SystemRequirementsandPrerequisitesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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
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.
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.
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
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.
MicrosoftEnterpriseLibrary5.0
TheInstanceCreationandDependencyInjectionMechanism
EnterpriseLibraryincorporatesaneasy-to-usemechanismforcreatingandwiringinstancesofobjects(whichmaycontainotherdependentobjects),andmanagingtheirlifetimes.ThisfeatureistheUnitycontainerandthefollowingdesignpatternsareused:
DependencyInjectionInversionofControl(IoC)ServiceLocatorServiceContainerFactoryBuilder
UnityandEnterpriseLibraryToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
PartialMigrationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
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,
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.
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
UpdatingConfigurationSettingsatRunTimeEncryptingConfigurationDataEnablingInstrumentationSourceSchemaforEnterpriseLibraryCore
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingtheConfigurationTools
TheEnterpriseLibraryconfigurationtoolsaregraphicaltoolsthatallowyoutocreate,change,andvalidateapplicationblocksettingswithouthavingtomanuallyedittheXMLconfigurationfileswheretheyarestored.ThereisaconfigurationeditorthatintegrateswithVisualStudio2008,plusstandaloneversionsfordifferentoperatingsystemandMicrosoft®.NETFrameworkversionsthatyoucanlaunchfromwithinVisualStudiooropenfromyourStartmenu.
Thesetoolsdisplaytheavailableconfigurationsettings,thedefaultvaluesthatyoucanchange,andinformationaboutwhateachsettingmeans.
Thistopiccontainsthefollowingsections:LaunchingConfigurationEditorfromVisualStudioSettingtheVisualStudioConfigurationEditorastheDefaultEditorLaunchingtheStandaloneConfigurationToolUsingWizardsintheConfigurationToolUsingtheKeyboardwiththeConfigurationToolTheConfigurationTypeSelectorEnterpriseLibraryConfigurationSchemaBuildingtheConfigurationConsoleSpecifyingDifferentAssembliesConfigurationToolUsageNotes
LaunchingtheConfigurationEditorfromVisualStudio
SettingtheVisualStudioConfigurationEditorastheDefaultEditor
LaunchingtheStand-aloneConfigurationTool
UsingWizardsintheConfigurationTool
UsingtheKeyboardwiththeConfigurationTool
TheConfigurationTypeSelector
EnterpriseLibraryConfigurationSchema
BuildingtheConfigurationConsole
SpecifyingDifferentAssemblies
ConfigurationToolUsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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:
UsingaNon-defaultConfigurationStoreSharingtheSameConfigurationbetweenMultipleApplicationsManagingandEnforcingConfigurationforMultipleApplicationsSharingConfigurationSectionsacrossMultipleApplicationsApplyingaCommonConfigurationStructureforApplicationsManagingConfigurationinDifferentDeploymentEnvironments
Youcanalsochangethecontentsofaconfigurationfileprogrammatically,whichisusefulwhenworkingwithsharedconfigurationstoredasdiskfiles.Formoreinformation,seeUpdatingSharedConfigurationSettingsProgrammatically.Forlinkstorelatedtopicsandmoredetailsofhowtheconfigurationsystemworks,seeMoreInformationattheendofthistopic.
SharingtheSameConfigurationbetweenMultipleApplications
ManagingandEnforcingConfigurationforMultipleApplications
SharingConfigurationSectionsacrossMultipleApplications
ApplyingaCommonConfigurationStructureforApplications
ManagingConfigurationinDifferentDeploymentEnvironments
UpdatingSharedConfigurationSettingsProgrammatically
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
clickingtheellipsisbutton(…)andnavigatingtothefileyouwanttouse.Thefilecanbelocatedonthelocalmachine,orinasharedlocationifyouwanttousethesameconfigurationformultipleapplicationsorapplicationlayers.
6. EdittheNamepropertyoftheconfigurationsourceifrequired.7. ClicktheConfigurationSourcespropertyexpanderchevrontoopen
thepropertiespaneforthesection.SettheSelectedSourcepropertybyselectingtheconfigurationsourceyouwanttouseforyourapplicationfromthedrop-downlist.
8. OntheFile,menuclickSaveorSaveAs.
Note:AQuickStartsamplenamedSqlConfigurationthatimplementsanexampleSQLConfigurationSourcetodemonstratehowyoucanstoreconfigurationinformationinadatabaseisavailablefromtheEnterpriseLibraryContribWebsite.ThisproviderusestheDataAccessApplicationBlocktoreadconfigurationsettingsfromaSQLServer©database.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
configurationsourcebytypingthepathandfilenameorbyclickingtheellipses(...)buttonandnavigatingtothefile.
5. YoucannowredirectsectionsfromyourlocalsourcetoanotherusingtheRedirectedSectionspane.ClicktheplussigniconintheRedirectedSectionscolumnandclickAddRedirectedSection.
6. InthenewRedirectedSectionthatisdisplayed,selecttheconfigurationsectionthatyouwanttoredirecttoasharedconfigurationsource.Afteryouselectthesection,thenameoftheredirectedsectionchangestoreflectthis.
7. Selecttheconfigurationsourcethatwillexposethesharedconfigurationsectionyouwanttouseinthedrop-downlistfortheConfigurationSourcepropertyoftheredirectedsection.Aconnectinglineappearsshowingwhichconfigurationsourcewillprovidetheinformationfortheredirectedsection.
8. ClickSaveorSaveAstosavetheconfiguration.
Note:IntheConfigurationTool,whenredirectedsectionsareusedwithaSelectedSourceotherthanSystemConfigurationSource,theredirectedsectionsconfigurationinformationwillstillbesavedtotheSystemConfigurationSource,whichisthefileopenedintheconfigurationtool.Toeditthecontentsofthesharedconfigurationsections,opentheconfigurationthatcontainsthemdirectly.
AnExampleoftheXMLGeneratedbyRedirectedSectionsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
5. ClicktheConfigurationSourcespropertyexpanderchevrontoopenthepropertiespaneforthesection.SettheParentSourcepropertytotheconfigurationsourcewhosesettingsyouwanttoinherit.
6. ClickSaveorSaveAsontheFilemenutosaveyourconfiguration.
Settingsintheinheritedconfigurationsourcewillapplytoyourapplicationunlessyouoverridethembyconfiguringthesamesettinginyourlocalconfiguration.Forinformationabouthowsettingsareinheritedandmerged,seeMergeRulesforInheritedConfiguration.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,pleasesendemailto
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
Whencreatingacompositeconfiguration,thereisahierarchytothecomponentsmergedintoyourEnterpriseLibraryconfigurationatruntime,asdescribedinAdditiveMergebelow.Inaddition,thereisahierarchyformergingofthecollectionsfromthespecifiedsources,describedinthesectionMergedCollectionsOrderlaterinthistopic.
AdditiveMerge
MergedCollectionsOrderToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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>
RedirectionandInheritanceConfigurationPropertyandAttributeSettings
SavedConfigurationSettingsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingGroupPolicywithEnterpriseLibrary
GroupPolicyprovidesacentralizedone-to-manymanagementcapabilityforWindowsthatallowsadministratorstodefinesettingsthatapplytoagroupofcomputers,systems,services,orapplications.GroupPolicyreliesontheActiveDirectory®servicetomanagethesettingsappliedatruntimetomembersoftheActiveDirectoryforest,domain,orsubgroup.FormoreinformationaboutGroupPolicy,seeGroupPolicyonMSDN.
EnterpriseLibraryincludesamanageableconfigurationsource.ThisallowsyoutouseGroupPolicytomanageanEnterpriseLibraryapplication.Youdonotneedtowriteanyapplicationcodetousethesefeatures.ThistopicprovidesinformationaboutthefollowingtasksforusingGroupPolicy:
AddingaManageableConfigurationSourceGeneratingandInstallingGroupPolicyTemplatesTroubleshootingGroupPolicy
AddingaManageableConfigurationSource
GeneratingandInstallingGroupPolicyTemplates
TroubleshootingGroupPolicy
AdministratorEntersInvalidValues
ApplicationIsModifiedWithoutGeneratingNewGroupPolicyTemplate
PoliciesConflicttoProduceInvalidConfiguration
OtherErrorsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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.
3. Intheeditpane,settheproperties.TheEnvironmentDeltaFilepropertyisthenameofthedeltafile.Ifyouwanttoencryptthefile,settheProtectionProviderpropertybyselectingaproviderfromthedrop-downlist.TheEnvironmentConfigurationFilepropertyisthenameofthemergedconfigurationfile.TheEnvironmentNamepropertyisthenameoftheenvironment.
4. Repeatthepreviousstepsforeachenvironmentyouwanttocreate.5. Tocustomizeablock'spropertiesforthisenvironment,addthe
applicationblocktotheconfiguration.OpentheBlocksmenuandselecttheblockyourequirebyclickingonitssettings;forexample,AddLoggingSettings.
6. Clicktheblockspropertiesexpanderarrowtoviewthelistofproperties.IntheOverrideson[environmentname]drop-downbox,clickOverridePropertiestoenablesettingtheblock'spropertiesforthisenvironment.
Note:Ifyourenameanenvironment,theupdatednamemaynotbedisplayedintheOverrideson[environmentname]property.However,itwillbeshownthenexttimeyouopentheconfigurationinthetool.
7. Clicktheexpanderarrowontheleftofthenamedenvironmentlistedundertheblock'sproperties,inthisscreenshottotheleftofOverridesonTestPlatform,todisplaythepropertiesforthatnamedenvironment.Youcanthenuseeachpropertydrop-downeditboxtoeditthepropertiesappropriatelyforyourrequirements.
8. Repeatsteps4,5and6foreachblockyouwanttocustomize.
Note:Theconfigurationtoolallowsyoutoaddmorethanoneadditionalenvironment.Eachconfigureditemthendisplaysasetofpropertiesforthebaseconfigurationfileandasetofpropertiesspecifictoeachofthenamedenvironments(withtheexceptionofpropertiesthatcannotbeoverridden).Thisenablesyoutoeditthebaseconfigurationfilepropertiesorthedeltafilepropertiesforaspecificnamedenvironment.
Tocustomizeablock'schildelementpropertiesforarun-timeenvironment1. Clickonthechildexpanderarrowtotheleftoftheblockname
—LoggingSettingsinthisexample—todisplaythechildelementsiftheyarenotalreadyvisible.
2. Ineachofthechildelementsthatyouwanttoconfigurefordifferent
environments,clickonthepropertyexpanderfortheenvironmentyouwanttoedit—OverridesonTestPlatforminthisexample.
3. SettheOverrideson[environmentname]propertytoOverrideProperties,andtheneditthepropertiesyouwanttooverrideforthatenvironment.ThisscreenshotshowshowyoucanspecifydifferentpropertyvaluesforaLoggingblockcategoryfilterandatargetlistenerindifferentenvironments.
Tosaveaconfiguration(.config)fileandadeltaenvironment(.dconfig)file1. SelectSaveorSaveAsontheFilemenutosaveboththenamed
environmentconfigurationfileandthedeltafile;ifeitherfilenameisblankyouwillbepromptedtoselectapathandfilename.
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
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.
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.
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()_
.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
TheCachingApplicationBlock
TheCryptographyApplicationBlock
TheDataAccessApplicationBlock
TheExceptionHandlingBlock
TheLoggingApplicationBlock
TheSecurityApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingtheappSettingsSection
YoucanusetheconfigurationtoolstocreateandmodifyMicrosoft.NETFramework<appSettings>sections.Notethatthe<appSettings>sectionsmustbeincludedinasinglefile;theyshouldnotbedistributedacrossmultiplefiles.ExamplesoffilesthatyoucannoteditincludetheMachine.configfileand<appSettings>sectionsthatincludetheoptionalfileattributethatspecifiesarelativepathtoanexternalconfigurationfile.
Configurean<appSettings>SectionUsingtheConfigurationTool
Configurean<appSettings>SectionbyEditingtheXMLToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
DetectingConfigurationChangesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
MicrosoftEnterpriseLibrary5.0
EnablingInstrumentation
Theterminstrumentationreferstoasystem'sbuilt-inabilitytomonitorormeasureperformanceandtodiagnoseerrors.EnterpriseLibraryincorporatesthefollowinginstrumentationinthemajorityoftheapplicationblocks:
Eventlogs.Theapplicationblocksinformusersofkeyevents,suchaserrorsorwarnings.Performancecounters.Theapplicationblocksrecordkeymetrics—suchasthenumberofcriticaleventsthatoccurpersecondortheaveragetimeittakestocompletekeytasks—bywritingtotheMicrosoftWindows®operatingsystemperformancecounters.
FordetailsofthedesignoftheEnterpriseLibraryinstrumentation,seeInstrumentation.
EnablingandDisablingInstrumentation
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
enterpriseLibrary.ConfigurationSourceElement
sourcesElement
instrumentationConfigurationChildElementToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
yourownscenarios.CreatingandReferencingEnterpriseLibraryObjects.ThistopicdescribesthevariouswaysofaccessingEnterpriseLibraryobjects,whattheiradvantagesanddisadvantagesare,anddetailsofhowtheyworkintheunderlyingcode.
Forinformationabouthowtocompiletheapplicationblocks,seeBuildingEnterpriseLibraryfromtheSourceCode.Forinformationaboutthedesignofthedependencyinjectionmechanism,seeTheDependencyInjectionModel.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
EnterpriseLibraryNamespacesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DependenciesinEnterpriseLibrary
ThistopicdescribesthedependenciesbetweentheblocksandonthecorefeaturesofEnterpriseLibrary.Itcontainsthefollowingsectionsthatdescribetheinter-blockdependenciesforcommonscenarios:
DependenciesforAllApplicationBlocksBlockDependencySchematicAdditionalDependenciesfortheCachingApplicationBlockAdditionalDependenciesfortheExceptionHandlingApplicationBlockAdditionalDependenciesforthePolicyInjectionApplicationBlockAdditionalDependenciesfortheSecurityApplicationBlock
DependenciesforAllApplicationBlocks
BlockDependencySchematic
AdditionalDependenciesfortheCachingApplicationBlock
AdditionalDependenciesfortheExceptionHandlingApplicationBlock
AdditionalDependenciesforthePolicyInjectionApplicationBlock
AdditionalDependenciesfortheSecurityApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
InjectionModelinthesection"DesignofEnterpriseLibrary".UsingthelegacystaticfacadesandfactoriesthatwerethedefaultapproachinpreviousversionsofEnterpriseLibrary.Formoreinformationaboutthese,seeLegacyStaticFacadesandFactories.
UsingtheUnityServiceLocator
AccessingtheUnityContainerDirectly
Non-StaticInstancesandInstanceFactories
LegacyStaticFacadesandFactories
InitializingandSettingtheCurrentContainer
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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.
container.
Disposethecontainer.
Whentheapplicationshutsdown.
Whereappropriateinthecode.
ResolvinganEntireObjectGraphatApplicationStartup
ResolvingandInjectingObjectsonDemand
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WindowsFormsandWPFApplications
Althoughtheyareverydifferenttechnologies,WindowsFormsandWindowsPresentationFoundation(WPF)sharesomefundamentalcharacteristics.Inparticular,theybothusewindowobjectstoimplementtheuserinterfaceandallowyoutospecifywhichcodeshouldrunwhentheapplicationstartsup.Bydefault,thestartupcodesimplyloadsandshowsthemainwindow,butyoucaneasilymodifythistocreateaUnitycontainer,populateitwiththeEnterpriseLibraryconfigurationinformation,andresolvetheobjectsusedbytheapplication.
Forexample,youmaynotwishtocreateallofthewindowsatstartuptominimizestartuptimesormemoryusage.Youcanstoreareferencetothecontaineranduseittoresolvewindowsandothertypesondemand.
Thefollowingsectionscontainmoredetails:WindowsFormsApplicationsWindowsPresentationFoundationApplications
WindowsFormsApplications
WindowsPresentationFoundationApplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
TheBasicApproach
RecommendedApproachforDependencyInjection
LimitationsandAlternativeApproachesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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(){}
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;
}
}
}
}
}
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()
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.
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
{
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
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WCFandASP.NETWebServiceApplications
ToinitializethecontainerandpopulatedependenciesinaWebserviceapplicationrequiresadifferentapproachfromthetypesofapplicationsthatexposeauserinterface(suchasWindowsForms,WPF,andASP.NETWebForms).ThistopicdescribesapossiblesolutionforASP.NETWebservices(ASMX),andpointstoresourcesthatwillhelpyouimplementtheprocessinaWindowsCommunicationFoundation(WCF)application.
ASP.NETWebServiceApplications
WCFApplicationsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CreatingApplicationBlockObjects
YoucanresolveinstancesofbothEnterpriseLibraryobjectsandyourowncustomclassesusingthecontainer.TounderstandhowtoresolvetheappropriateEnterpriseLibraryobjects,youmustbeawareofthewaythattheEnterpriseLibraryconfigurationinformationforyourapplicationmapstotheregistrationsinthecontainer.
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.
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.
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.
FormoredetailedinformationaboutthedependencyinjectionfeaturesofUnity,seeUnityDependencyInjectionandInterception.
UsingConstructorInjection
UsingPropertyInjection
UsingMethodCallInjectionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ResolvingInstancesofTypesUsingUnity
ThistopicdiscussesthemethodsthatUnityprovidesforresolvingtypesandcreatinginstancesoftypes.ItalsodescribeshowyoucanresolveinstancesofEnterpriseLibraryobjectsandyourowncustomtypes.Thetopicsarethefollowing:
TheUnityResolveMethodResolvingInstancesofEnterpriseLibraryTypesResolvingInstancesofYourOwnCustomTypes
Note:Othertopicsinthissectionshowhowyoucaninjectresolvedinstancesintoyourowncustomclasses,andhowyoucancreateinstancesofEnterpriseLibraryobjectsdirectly.Formoreinformation,seeInjectingResolvedTypesintoOtherClassesandCreatingApplicationBlockObjectsDirectly.
TheUnityResolveMethod
ResolvingInstancesofYourOwnCustomTypesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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)
ConfigurationInformationforNewObjectsSomeobjectconstructorshaveanoverloadthatacceptsaninstanceofaconfigurationsourcethatimplementstheIConfigurationSourceinterface.Thisallowsyoutosupplyconfigurationinformationdirectlytothenewobject.
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
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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.
MicrosoftEnterpriseLibrary5.0
PreparationandVersioning
WhenyoucompiletheinstalledversionoftheEnterpriseLibrarysourcecode,theassembliesproducedwillnotbestrongnamed.Asaresult,theycannotbeinstalledintheglobalassemblycache,norwilltheyhavetheotherbenefitsassociatedwithstrong-namedassemblies.
UsingXCopy
UsingtheGlobalAssemblyCache
VersioningToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
BuildingEnterpriseLibraryfromtheSourceCode
AlthoughtheEnterpriseLibraryincludesbinariesforallthesourcecode,youmaywanttocustomizethesourcecode.ThismeansyouwillneedtobuildtheEnterpriseLibraryyourself.Thefollowingsectionsdescribehowtodothis.Afteryouhavethebinaries,youmaywanttostrongnamethem.Formoreinformationaboutthistopic,seeStrongNamingtheEnterpriseLibraryAssemblies.
Thistopiccontainsthefollowingsubsections:InstallingtheSourceCodeEnterpriseLibraryVisualStudioSolutionFilesBuildingtheEnterpriseLibraryApplicationBlocksandToolsBuildingtheEnterpriseLibraryUsingMicrosoft.NetFramework4.0AdditionalNotesforBuildingandUsingtheSourceCode
InstallingtheSourceCode
EnterpriseLibraryVisualStudioSolutionFiles
BuildingtheEnterpriseLibraryApplicationBlocksandTools
AdditionalNotesforBuildingandUsingtheSourceCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
UsingVisualStudiotoStrongNameEnterpriseLibraryAssembliesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UpdatingApplicationBlockAssemblies
IfanupgradedversionofanEnterpriseLibraryApplicationBlockbecomesavailable,youcaninstallthenewversionandhaveallapplicationsusetheupdatedassembly.However,ifthenewversionintroducescompatibilityproblemsforcertainapplications,youcaninstallthenewversionintheglobalassemblycacheandconfiguresomeapplicationstousetheupdatedversion,whileotherscontinuetousetheearlierversion.
UpdatingPrivateAssemblies
UpdatingSharedAssembliesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
PartialTrustEnvironments
ApplicationsthatuseversionsoftheEnterpriseLibrarypriortoversion3.0requireenoughpermissionssothattheonlysecurityleveltheycanuseisfulltrust.WithlaterversionsofEnterpriseLibrary,includingthisversion,youcanrunapplicationsunderpartialtrust.AcommonexampleisanASP.NETapplicationthatrunsinahostedenvironment.Typically,thesetypesofapplicationsrequireonlyenoughpermissionstorunundermediumtrust.DependingontheEnterpriseLibraryfeaturesthatyourapplicationuses,youmayneedtograntadditionalpermissionsbeyondthosegrantedbyadefaultpartial-trustpolicy.
Thistopiccontainsthefollowingsections:OverviewofPartialTrustEnterpriseLibraryandPartialTrustEnterpriseLibraryCodeAccessSecurityandtheSecurityTransparentAttribute
OverviewofPartialTrust
EnterpriseLibraryandPartialTrust
EnterpriseLibraryCodeAccessSecurityandtheSecurityTransparentAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CustomizingtheMediumTrustPolicy
Thetablesinthefollowingsectionsshowtheadditionalpermissions—beyondthosegrantedbydefaultinthemediumtrustpolicy—thatmayberequiredbyyourapplication.Youneedtogranttheseadditionalpermissionsonlyifyouwanttousethesespecificfeatures.Unlessotherwisenoted,makethesemodificationsinthecustompolicyfile.
Forextendedexamplesofhowtomodifyacustompolicyfile,seeHowTo:UseMediumTrustinASP.NET2.0onMSDN.Ifyouareusingapartial-trustpolicyotherthanmediumtrust,otherrestrictionsandpermissionsmayapply.Foratablethatliststhedifferentpermissionsandthetrustpoliciesthatallowthem,seeASP.NETCodeAccessSecurityonMSDN.
Theseadditionalpermissionsarethefollowing:GeneralPermissionsCachingApplicationBlockPermissionsCryptographyApplicationBlockPermissionsDataAccessApplicationBlockPermissionsExceptionHandlingApplicationBlockPermissionsLoggingApplicationBlockPermissionsSecurityApplicationBlockPermissionsPolicyInjectionApplicationBlockPermissionsValidationApplicationBlockPermissions
Thenextsectionsdescribethesepermissions.
GeneralPermissions
CachingApplicationBlock
CryptographyApplicationBlock
DataAccessApplicationBlock
ExceptionHandlingApplicationBlock
LoggingApplicationBlock
SecurityApplicationBlock
PolicyInjectionApplicationBlock
ValidationApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LimitationsWhenUsingPartialTrust
TheremaybesomelimitationsregardinghowyouusepartialtrustwithanEnterpriseLibraryapplicationblock.Theselimitationsincludethefollowing:
EnterpriseLibrarythrowsaSecurityExceptionifitcannotobtainthemandatorypermissions.SomecallstoLoggingApplicationBlocktracelistenerclassesfail.ASP.NETapplicationdirectoriesrequirespecificpermissions.TheAzManproviderisnotavailablewithpartialtrust.
EnterpriseLibraryThrowsSecurityException
LimitationsonLoggingApplicationBlockTraceListeners
ASP.NETApplicationDirectoriesRequirePermissions
AzManProviderNotAvailableToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
AdministeringEnterpriseLibrary
ThistopicdescribessomeofthemainscenariosforsystemadministratorsandoperatorswhomanageapplicationsthatuseEnterpriseLibrary.Ingeneral,theprocessesandtechniquesarenodifferentfromthoseinvolvedinmanagingany.NETapplication.However,EnterpriseLibrarydoesprovideseveralusefulfeaturesdesignedtomakeadministrationandmanagementeasier.Thissectioncoversthefollowingtopics:
RunningMultipleVersionsofEnterpriseLibraryRunTimeConfigurationChangestotheRunTimeEnvironmentInstrumentationwithintheApplicationBlocksIntegrationwithEnterpriseManagementToolsDebuggingUsingtheSourceCode
RunningMultipleVersionsofEnterpriseLibrary
RunTimeConfiguration
ChangestotheRunTimeEnvironment
InstrumentationwithintheApplicationBlocks
IntegrationwithEnterpriseManagementTools
DebuggingUsingtheSourceCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
GuidelinesforExtendingEnterpriseLibrary
GuidelinesforModifyingtheApplicationBlocksToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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:
ThissectiondoesnotcoverextendingtheUnitydependencyinjectionandinterceptionmechanism.ForinformationabouthowyoucanextendUnity,seethedocumentationavailableontheUnityWebsiteathttp://www.codeplex.com/unity/.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
EnterpriseLibraryExtensionPoints
ThefollowingtableslisttheextensionpointsthatEnterpriseLibraryprovidesforeachoftheapplicationblocks.Foreachtypeofproviderorextension,thetablesshow:
Theinterfaceyoucanimplementand/orthebaseclassyoucaninherit.Thetypeoftheconfigurationelementtoapplytoyourcustomclasstoenablebasicintegrationwiththeconfigurationsystem.Thebaseclassthatyoumustinheritinyourcustomconfigurationelementifyouwanttoimplementfulldesign-timeconfigurationintegration.Yourcustomproviderorextensionwillthenuseyourcustomconfigurationelementclassasitsconfigurationelementtype,insteadofthedefaultshownintheConfigurationElement(basicintegration)column.
ProvidersandextensionsthatcannotbeintegratedwiththeconfigurationtoolshavenoentryintheConfigurationElement(basicintegration)column.
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
CryptographyApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
HashAlgorithmProvider
IHashProvider CustomHashProviderData
SymmetricEncryptionAlgorithmProvider
ISymmetricCryptoProvider CustomSymmetricCryptoProviderData
DataAccessApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
DatabaseProvider
Database n/a n/a
ExceptionHandlingApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
ExceptionHandler
IExceptionHandler CustomHandlerData ExceptionHandlerData
ExceptionFormatter
ExceptionFormatter n/a n/a
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.
PolicyInjectionApplicationBlockPolicyinjectionisafeaturedrivenbytheUnityinterceptionmechanism.Youcancreatecustombehaviors,callhandlers,callhandlerattributes,andmatchingrulesforusewiththeUnityinterceptionmechanism.Formoreinformation,seehttp://www.codeplex.com/unity/.
SecurityApplicationBlock
CustomProviderorExtension
InterfaceorBaseClass
ConfigurationElement(basicintegration)
ConfigurationElementBaseClass(designtimeintegration)
AuthorizationProvider
AuthorizationProvider CustomAuthorizationProviderData AuthorizationProviderData
SecurityCacheProvider
ISecurityCacheProvider CustomSecurityCacheProviderData SecurityCacheProviderData
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.
MicrosoftEnterpriseLibrary5.0
EnterpriseLibraryConfigurationIntegration
EnterpriseLibraryallowsyoutoeasilyintegratecustomprovidersandextensionsintothelibraryinsuchawaythatyoucanconfigurethemusingtheEnterpriseLibraryconfigurationtools.Therearetwotypes,orlevels,ofconfigurationintegration.
BasicConfigurationIntegration
FullConfigurationIntegrationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CreatingaCustomProvider
Thefollowingstepsdescribetheprocessforcreatingacustomprovider:PreparingYourProjectImplementingtheInterfaceorExtendingtheBaseClassSpecifyingtheConfigurationElementTypeAddingFullDesign-timeIntegrationSummaryofSteps
PreparingYourProject
ImplementingtheInterfaceorExtendingtheBaseClass
SpecifyingtheConfigurationElementType
AddingFullDesign-timeIntegration
SummaryofStepsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
Plug-inPattern
DependencyInjectionPatternToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheEnterpriseLibraryCore
ManytasksthattheEnterpriseLibraryapplicationblocksperformarecommonacrossmorethanoneapplicationblockandarealsousefulinapplicationcodeoutsideofEnterpriseLibrary.Examplesareroutinesthatserializedataoraccessconfigurationinformation.Topromoteusability,theseroutinesresideinacommonassemblynamedtheEnterpriseLibraryCore.
Inaddition,alltheapplicationblocksaredesignedtohavealimitednumberofdependenciessothattheycanbeusedindividuallyaswellaswithotherapplicationblocks.AllapplicationblocksexceptUnitydependontheEnterpriseLibraryCore,whichisalogicalgroupingmadeupofthefollowingsubsystems:
TheCommonassemblyInstrumentationfortheapplicationblocksConfigurationhelperclassesanddesign-timeconfigurationcomponents
ForinformationaboutthedependenciesbetweenapplicationblocksandtheEnterpriseLibraryCore,seeDependenciesinEnterpriseLibrary.
TheCommonAssembly
Instrumentation
ConfigurationHelperClassesandDesign-timeComponentsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
ApplicationBlockwouldrequireonlyanewlogginghandlerprovider;therestoftheExceptionHandlingApplicationBlockcanremainunchanged.
Forinformationaboutcreatingyourownprovidersfortheapplicationblocks,seethe"ExtendingandModifying"sectionofthedocumentationforeachapplicationblock.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignTimeConfiguration
Allapplicationblocksincludebothrun-timesupportanddesign-timesupportforconfigurationsettings.Therun-timesupportincludesclassesthatrepresenttheconfigurationsettings.TheConfigurationApplicationBlockusestheseclassdefinitionswhenitloadsconfigurationsettings.Itreadstheconfigurationsettingsfromstorageandreturnsobjectsthatcontaintheconfigurationdatatotheapplicationblock.
Thedesign-timeconfigurationsupportincludesclassesthatallowyoutochangetheconfigurationsettingsbyusingtheEnterpriseLibraryconfigurationtools.Theseclassesdefineavisualrepresentationofthedifferentconfigurationsettings,specifytheactionsthatcanbeperformedbasedonthecurrentconfigurationstate,andprovidetheabilitytovalidatetheconfigurationsettings.
Thefollowingfigureillustratestherelationshipbetweentherun-timeconfigurationsupportandthedesign-timeconfigurationsupport.
Thedesign-timeclassesdependontheconfigurationrun-timeclassesbecause
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.
MicrosoftEnterpriseLibrary5.0
TheDependencyInjectionModel
ThistopicdescribesthemechanismusedbyEnterpriseLibrarytocreateandmanagethelifetimeofobjectswithinthecoreandtheapplicationblocks.EnterpriseLibraryusesadependencyinjectionmechanismtocreateandmanagethelifetimeofalltheEnterpriseLibraryobjectsitcreates.Dependingonthestyleofyourapplication,itmayusethesamedependencyinjectioncontainerthatEnterpriseLibraryuses.Thistopiccontainsthefollowingsections:
ApplicationandContainerInitializationUsinganAlternativeDependencyInjectionContainerMoreInformation
TolearnhowtousetheUnitydependencyinjectionapproachwhenwritingapplicationcode,seeUsingEnterpriseLibraryinApplications.
UsinganAlternativeDependencyInjectionContainer
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
theblockthroughaconstructorparameter.TheCacheclass,forexample,takesanICachingInstrumentationProviderasshownhere.C#
publicclassCache:ICacheOperations,IDisposable
{
publicCache(IBackingStorebackingStore,
ICachingInstrumentationProviderinstrumentationProvider)
{
...
}
...
}
Becausetheimplementationsfortheinstrumentationproviderinterfacesareregisteredwithinthedependencyinjectioncontainer,theyareinjectedintotheclassesthatrequirethem.
HowInstrumentationProvidersWorkToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
GroupPolicySupport
ThisreferencesupplementstheinformationinUsingGroupPolicywithEnterpriseLibrary.Itisdividedintothefollowingsections:
TheManageableConfigurationSourceClass.ThissectiondescribesthedesignoftheclassthatprovidesGroupPolicyconfigurationsupportinEnterpriseLibrary.IntegrationofGroupPolicywithEnterpriseLibraryApplications.ThissectionprovidesinformationabouthowinstancesoftheManageableConfigurationSourceareintegratedwithGroupPolicyandincludesinformationaboutGroupPolicytemplatestructure.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheManageableConfigurationSourceClass
ThistopicdescribestheclassesthatmakeuptheManageableConfigurationSourceclass.
ManageableConfigurationSource
ManageabilityHelperToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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:
GroupPolicyTemplateStructureGeneralSettingsfortheApplicationBlocksExceptionstotheGeneralTemplateStructureApplyingGroupPolicySettingsLimitationsofGroupPolicySupport
GeneralSettingsfortheApplicationBlocks
ExceptionstotheGeneralTemplateStructure
ApplyingGroupPolicySettings
LimitationsofGroupPolicySupportToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UnitTests
EnterpriseLibraryincludesVisualStudio®solutionfilesthatincludeVisualStudioTeamSystemunittestswiththeapplicationblockprojects.YoucanusethemainEnterpriseLibrarysolutionfile(EnterpriseLibrary.VSTS.sln)tobuildtheentireEnterpriseLibrarywiththeunittests.ThissolutioncontainstheentiresetofapplicationblockprojectsandtheEnterpriseLibrarycoreprojects,andincludesallunittestsforexecutionwiththeVisualStudioTeamSystem.
TheEnterpriseLibrarysolutionfilesincludetwobuildconfigurations:ReleaseandDebug.Allprojectswithinasolutionfilearecompiledinbothconfigurations,includingtheunittestprojects.Formoreinformation,seeBuildingEnterpriseLibraryfromtheSourceCode.
Note:ThisreleaseofEnterpriseLibrarydoesnotincludesolutionsthatusetheNUnittestframework.
SoftwareRequirements
UsingtheUnitTestsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
block.WhenShouldIUsetheCachingApplicationBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andanyalternativetechniquesyoumayconsider.Italsoprovidesdetailsofanylimitationsoftheblockthatmayaffectyourdecisiontouseit.DevelopingApplicationsUsingtheCachingApplicationBlock.ThistopicfirstexplainshowtoconfiguretheCachingApplicationBlockandaddittoyourapplication.Itthenexplainshowtoselectabackingstore.KeyScenarios.Thissectiondemonstrateshowtousetheblocktoperformtypicalcachingoperations.DesignoftheCachingApplicationBlock.ThistopicexplainsthedecisionsthatwentintodesigningtheCachingApplicationBlockandtherationalebehindthosedecisions.ExtendingandModifyingtheCachingApplicationBlock.Thistopicexplainshowtoextendtheblockbyaddingyourownbackingstoreandyourownexpirationpolicies.Italsoexplainshowtomodifyitbychangingthesourcecode.DeploymentandOperations.ThistopicexplainshowtodeployandupdatetheCachingApplicationBlockassemblies.
MoreInformationForrelatedinformation,seethefollowingpatterns&practicesguidesanddocuments:
MicrosoftApplicationArchitectureGuide,2ndEditionCachingArchitectureGuidefor.NETFrameworkApplicationsEnterpriseLibraryhomepageonMSDN®EnterpriseLibraryontheCodePlexWebsite
Forlinkstoexternalcachingproviders,seethe"MoreInformation"sectioninTheCachingApplicationBlockonMSDN.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
Note:Forinformationaboutthetypesofexpirationyoucanuse,andthedefaultexpirationfornewitems,seeDesignoftheExpirationProcess.
AsapplicationcodeinteractswiththeCacheManager,itupdatesthein-memorycacheand—ifabackingstoreisconfigured—updatesthebackingstore.Youcanconfigureanencryptionproviderforthebackingstore,whichisimplementedbytheCryptographyApplicationBlock,toencrypttheitemsthatarecachedinthebackingstore(notethattheblockdoesnotencryptitemsstoredinthein-memorycache).
TheblockincludesprovidersthatstoredatainadatabaseorinIsolatedStorageonthelocalmachine.Itdoesnotprovideadistributedcachingmechanism.Additionalproviders,includingprovidersthatsupportdistributedcaching,maybeavailablefromthirdpartiesandtheEnterpriseLibrarycommunityWebsite.Formoreinformation,seetheCodePlexCommunityandEnterpriseLibraryContributionsWebsites.
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheCachingApplicationBlock?
TheCachingApplicationBlockissuitableifyouencounteranyofthefollowingsituations:
Youmustrepeatedlyaccessstaticdataordatathatrarelychanges.Dataaccessisexpensiveintermsofcreation,access,ortransportation.Datamustalwaysbeavailable,evenwhenthesource,suchasaserver,isnotavailable.
YoucanusetheCachingApplicationBlockwithanyofthefollowingapplicationtypes:
WindowsFormsWindowsPresentationFoundation(WPF)WindowsCommunicationFoundation(WCF)ConsoleapplicationWindowsserviceASP.NETWebapplicationorWebserviceifyouneedfeaturesnotincludedintheASP.NETcache
ScenariosfortheCachingApplicationBlock
BenefitsoftheCachingApplicationBlock
LimitationsoftheCachingApplicationBlock
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheCachingApplicationBlock
ThissectiondescribeshowtousetheCachingApplicationBlocktodevelopapplications.Itexplainshowtoenterconfigurationinformationfortheblock,incorporateitintoyoursolution,andselectabackingstore.Thissectionincludesthefollowingtopics:
EnteringConfigurationInformationAddingApplicationCodeSelectingaBackingStore
Allblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompileit.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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
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
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.
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.
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
cachingConfigurationElement
encryptionProvidersElement
backingStoresElement
cacheManagersElement
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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#
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.
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.
UsageNotes
UsingtheNullBackingStore
UsingtheDataAccessApplicationBlockBackingStore
ConsiderationsforServerScenarios
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
MicrosoftEnterpriseLibrary5.0
AddingItemstotheCache
Cachesstoreitemsthatareeitherexpensivetocreateorexpensivetotransport.Forexample,inaretailapplication,alistofproductsmustbepassedfromthedataaccesscomponentstotheuserinterfacecomponentssothattheproductlistcanbedisplayedtotheusers.Thedatarepresentsreal-worldbusinessentities,suchasproductsororders.Toincreaseperformance,someoftheseitemsmaybeaddedtothecache.
TypicalGoals
Solution
UsingtheAddMethod
RefreshingRemovedItems
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RemovingItemsfromtheCache
Thescavengingandexpirationprocessesautomaticallyremoveitemsfromthecacheaccordingtotheprioritiesandexpirationpoliciesoftheitems.Youcanalsoremovespecificitemsfromthecache.Forexample,inaretailapplication,somedatamaynolongerbeapplicable,dependingonselectionsthecustomermakes.
TypicalGoals
Solution
UsingtheRemoveMethodToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RetrievingItemsfromtheCache
Datastoredinthecachemustberetrievedsothatitcanbedisplayedorprocessed.Forexample,inaretailapplication,youmaywanttodisplayalistofproductsfromacatalog.
TypicalGoals
Solution
UsingtheGetDataMethodToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
FlushingtheCache
Flushingletsyoumanagecacheditemstomakesurethatstorage,memory,andotherresourcesareusedefficiently.Flushingremovesallitemsinthecache,includingthosethathavenotyetexpired.Forexample,inaretailapplication,cacheddatamaynolongerbevalidbecauseofselectionsmadebythecustomerorbecausethecustomerhasloggedoff.
TypicalGoals
Solution
UsingtheFlushMethodToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LoadingtheCache
Beforeyoucanusecacheddata,youmustfirstloaddataintothecache.Forexample,inaretailapplication,youmaywanttoloaddataaboutvariousproducts,orallproducts,intothecache.
TypicalGoals
Solution
CachingDataProactively
LoadingExamplesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignoftheCachingApplicationBlock
TheCachingApplicationBlockisdesignedspecificallysothat:ItprovidesasetofAPIsthataremanageableinsize.Itenablesdeveloperstoincorporatethestandardcachingoperationsintotheirapplicationswithouthavingtolearntheinternalworkingsoftheblock.ItusestheEnterpriseLibraryconfigurationtoolsforeasyconfiguration.Itperformsefficiently.Itisthreadsafe.Codeisconsideredtobethreadsafewhenitcanbecalledfrommultipleprogrammingthreadswithoutunwantedinteractionamongthosethreads.Itensuresthatthebackingstoreremainsintactifanexceptionoccurswhileitisbeingaccessed.Itensuresthatthestatesofthein-memorycacheandthebackingstoreremainsynchronized.
Thistopicdescribesthedesignofthecachingsystem,describingthehighlightsandspecificdesigndetails.OthertopicsinthissectionincludeDesignoftheExpirationProcessandDesignoftheScavengingProcess.
DesignHighlights
DesignDetailsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
expirationpolicy,whichisNeverExpired.Theotheroverloadletsyousettheexpirationpoliciesyourself.Youcanuseasmanypoliciesasyouwant,includingpoliciesthatyoucreateyourself.(FormoreinformationaboutextendingtheCachingApplicationBlockbyaddingyourownexpirationpolicies,seeExtendingandModifyingtheCachingApplicationBlock.)Ifyouhaveanitemwithmultiplepolicies,theitemwillexpireifanyoneofthepolicy'scriteriaismet.
MarkingandSweeping
CallbacksToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
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.
AddingaNewBackingStore
AddingaNewExpirationPolicy
ReplacingtheDefaultCacheManagerToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetomakesurethattheinitialdeploymentoftheCachingApplicationBlockisplannedandmanagedandtomakesurethatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheCachingApplicationBlock,seethefollowingtopics:
CachingApplicationBlockPerformanceCountersCachingApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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.
MicrosoftEnterpriseLibrary5.0
CachingApplicationBlockEventLogEntries
ThistopicliststheCachingApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
CacheFailedEvent
CacheCallbackFailedEvent
ConfigurationErrorEvent
ConfigurationChangedEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
configuretheblockforcommonoperations.KeyScenarios.Thistopicthenshowshowtousetheblocktoperformmostcryptographytasks.DesignoftheCryptographyApplicationBlock.Thistopicexplainsthedecisionsthatwentintothedesignoftheblockandtherationalebehindthosedecisions.ExtendingandModifyingtheCryptographyApplicationBlock.ThistopicexplainshowtoextendtheCryptographyApplicationBlockbycreatingyourownprovidersandhowtomodifythesourcecode.DeploymentandOperations.Thistopicexplainshowtodeployandupdatetheblock'sassemblies.Italsocontainsinformationaboutconfiguration.
MoreInformationFormoreinformation,seethefollowingresources:
ImprovingWebApplicationSecurity:ThreatsandCountermeasuresHowTo:UseAuthorizationManager(AzMan)withASP.NET2.0patterns&practicesSecurityHowToIndex
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheCryptographyApplicationBlock?
YoushouldusetheCryptographyApplicationBlockwhenyouneedhashingand/orsymmetricencryptionfunctionality.Youcanusethesefunctionsinconjunctionwiththecryptographicprovidersincludedwiththeblockorwithyourowncustomcryptographicproviders.Ifthedataonlyneedstobeencrypted,anditdoesnotneedtobedecrypted(forexample,apassword),youcanusehashing.Ifthedataneedstobebothencryptedanddecrypted(forexample,totransmitsensitivecustomerdata),youcanusesymmetricencryption.
ScenariosfortheCryptographyApplicationBlock
BenefitsoftheCryptographyApplicationBlock
LimitationsoftheCryptographyApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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
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.
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.
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.
2. (Optional)Inthepropertiespane,settheDefaultHashProviderproperty.ThissetstheinstanceofthehashproviderthattheCryptographyApplicationBlockusesiftheapplicationcodedoesnotspecifyanotherprovider.Inthedrop-downlist,clickthehashprovider.Thedefaultisnone.
3. (Optional)Inthepropertiespane,settheDefaultSymmetricCryptoProviderproperty.ThissetstheinstanceofthesymmetriccryptographyproviderthattheCryptographyApplicationBlockusesiftheapplicationcodedoesnotspecifyanotherprovider.Inthedrop-downlist,clickthesymmetricprovider.Thedefaultisnone.
UsingtheCryptographicKeyWizard
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
securityCryptographyConfigurationElement
hashProvidersChildElement
symmetricCryptoProvidersChildElement
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
MaximizingSecurity
TwoimportantpointsyoushouldconsiderwhenyouusetheCryptographyApplicationBlockarehowyouaregoingtomanagesymmetricencryptionkeysandwhichhashingalgorithmorsymmetricencryptionalgorithmyouaregoingtouse.
ManagingandDistributingKeys
SelectinganEncryptionAlgorithmToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
Note:ForMicrosoft®VisualBasic®projects,youcanalsousetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer,andthenclickPropertiesontheProjectmenu.WhentheProjectDesignerappears,clicktheReferencestab.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
MicrosoftEnterpriseLibrary5.0
EncryptingDataUsingaSymmetricProvider
Acommoncryptographytaskistoencryptdatausingasymmetricprovider.Youmaywanttodothiswhenanapplicationhasdatayouwanttokeepsecure.
TypicalGoals
Solution
UsingEncryptSymmetric
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DecryptingDataUsingaSymmetricProvider
Ifyouencryptdatabyusingasymmetricencryptionprovider,youusuallyhavetodecryptthedatausingthesameprovider.
TypicalGoals
Solution
UsingDecryptSymmetric
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ObtainingaHashValue
Anexampleofwhenyoumightwanttoobtainahashvalueiswhenyouhaveapasswordthatyoudonotwanttopassoverthenetwork.
TypicalGoals
Solution
UsingCreateHash
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CheckingWhetheraHashValueMatchesSomeText
Anexampleofwhenyouwouldcheckwhetherahashmatchessometextiswhenyouhavetoverifythatdatahasnotbeenchangedintransitoveranetwork.Inthiscase,thehashvalueforthedatawouldbestoredattheserver,andwhenthedataarrivesattheserver,itiscomparedagainstthehashvalue.
TypicalGoals
Solution
UsingCompareHash
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignoftheCryptographyApplicationBlock
Thistopicdescribesthedesigngoals,designhighlights,andtheimplementationoftheCryptographyApplicationBlock.
DesignGoals
DesignHighlights
KeyManagementModelToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesigningforSimplifiedCryptographyFunctionality
Cryptographyinapplicationscanbeimplementedinmanyways.Typically,developersmustduplicatecodetoperformcommontasks.Tomeettheneedsoftheirorganization,theymayhavetofamiliarizethemselveswithmanydifferentwaysofimplementingcryptography.TheCryptographyApplicationBlockisdesignedtosimplifyandabstracttheimplementationofcryptographyinapplications.
DesignImplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesigningforAlgorithmAbstraction
WiththeCryptographyApplicationBlock,developerscanrefertothealgorithmtobeusedbythevariousmethodsbyusinglogicalnames,suchas"hashprovider"or"passwordencryption."
DesignImplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ExtendingandModifyingtheCryptographyApplicationBlock
Initsoriginalstate,theCryptographyApplicationBlockworkswellfortypicalcryptographyscenarios.However,theremaybetimeswhenyouhavetocustomizesomeoftheblock'sbehaviortobettersuityourapplication'sparticularrequirements.Therearetwowaystocustomizetheblock,extensionandmodification.
ExtendingtheCryptographyApplicationBlock
ModifyingtheCryptographyApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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;
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
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;
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
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.
MicrosoftEnterpriseLibrary5.0
ModifyingtheCryptographyApplicationBlock
TheCryptographyApplicationBlockwasdesignedtobeusedinavarietyofapplicationsandtobeageneral-purposecryptographyapplicationblock.Extensionpointsletyouadapttheblocktosuittherequirementsofanyparticularapplication.However,ifyouwanttoaddnewfeaturestotheblock,youcandosobymodifyingthesourcecode(theblockincludesboththesourcecodeandthebinaries).
Note:Whenmodifyingthesourcecode,youshouldfollowgoodpracticesdescribedinthetopicExtendingandModifyingEnterpriseLibrary.
ModifyingtheKeyManagementCode
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetomakesurethattheinitialdeploymentoftheCryptographyApplicationBlockisplannedandmanagedandtomakesurethatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheblock.Fordetails,seeDeployingtheCryptographyApplicationBlock.
Inaddition,administratorsmustdecideiftheywanttousetheinstrumentationexposedbytheblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationontheinstrumentationcontainedwithintheCryptographyApplicationBlock,seethefollowingtopics:
CryptographyApplicationBlockPerformanceCountersCryptographyApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DeployingtheCryptographyApplicationBlock
TheCryptographyApplicationBlockiscomprisedofmultipleassemblies.EachassemblythatbelongstotheCryptographyApplicationBlockhasafilenamethatbeginswithMicrosoft.Practices.EnterpriseLibrary.Security.Cryptography.Additionally,theblockdependsonthecommonassemblyandontheUnitysubsystem.FordetailsofdeployingandupdatingEnterpriseLibraryandtheblocks,seeDeployingEnterpriseLibrary.
DistributingKeysToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CryptographyApplicationBlockEventLogEntries
ThistopicliststheCryptographyApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
CryptographicOperationFailedEvent(SymmetricAlgorithm)
CryptographicOperationFailedEvent(HashAlgorithm)
ConfigurationFailureEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
decisionsthatwentintodesigningtheapplicationblockandtherationalebehindthosedecisions.ExtendingandModifyingtheDataAccessApplicationBlock.Thissectiondescribeshowtoextendtheapplicationblockbyaddingyourowndatabaseproviderandgivessuggestionsformodifyingthesourcecode.DeploymentandOperations.Thissectiondescribeshowtodeployandupdatetheapplicationblockassemblies.ItalsocontainsinformationaboutconfigurationandMicrosoft®SQLServer®security.
MoreInformationFormoreinformation,seethefollowingresources:
MicrosoftApplicationArchitectureGuide,2ndEdition-Chapter8:DataLayerGuidelines.NETDataAccessArchitectureGuideINFO:MicrosoftGuideforDesigningDataTierComponentsandPassingDataThroughTiersImprovingWebApplicationSecurity:ThreatsandCountermeasuresImproving.NETApplicationPerformanceandScalability
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheDataAccessApplicationBlock?
YoushouldconsiderusingtheDataAccessApplicationBlockifyourapplicationusesstandarddataaccesstechniques.Theblockisparticularlysuitedtoquerying,retrieving,andupdatingdatathroughimplementationsbasedontheExecuteReader,ExecuteXmlReader,andExecuteNonQuerymethodscommonlyusedinADO.NET—includingtheasynchronousversionsofthesemethods.ItalsoprovidesmethodstopopulateDataSetinstances,andflushthechangesbacktothedatabase.
Youshouldalsoconsiderusingtheblockifyouwanttoworkwithdatausingclient-sidequeryingmechanismssuchasLanguageIntegratedQuery(LINQ).Itcontainssupportfortheseprogrammingtechniquesbyexposingmethodsthatreturndataassequencesofobjects.
AthirdreasonforusingtheDataAccessApplicationBlockisitscapabilitytoabstractthedatabasetype.Thismakesiteasiertochangeyourapplicationtouseadifferenttypeofdatabaseifrequired,althoughsomeofthemoreadvanceddataaccessmethodsdorelyonthespecificcapabilitiesoftheunderlyingADO.NETDataProvider.
ScenariosfortheDataAccessApplicationBlock
BenefitsoftheDataAccessApplicationBlock
LimitationsoftheDataAccessApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
.NETFramework4.0,see.NETFrameworkClientProfileonMSDN.Forinformationaboutchangingthetargetedprofile,seeHowto:TargetaSpecific.NETFrameworkVersionorProfileonMSDN.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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
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
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.
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
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
associatingaproviderwiththefullyqualifiednameofadatabase.
Toconfigureacustomprovider1. ClicktheplussigniconintheCustomDatabasespane,andthenclick
onAddCustomDatabaseProvider.2. (Optional)SettheNamepropertybytypinganewnameorselectit
fromthedrop-downlist.ThedefaultprovidernameisCustomDatabaseProvider.
3. IntheTypepropertytextbox,clicktheellipsisbutton(…)andusethetypeselectortoselectthefullyqualifiednameoftheEnterpriseLibrarydatabasetype.Iftheproviderisregisteredintheglobalassemblycache(GAC),clicktheAddfromGACbuttontolocateit.IfyouareusingtheVisualStudiointegratedconfigurationeditorandyoudonotseetheprovidertypeyourequireinthelist,youmustaddareferencetotheassemblycontainingtheprovidertoyourproject.
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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).
connectionStringsElement
dataConfigurationElement
providerMappingsChildElement
oracleConnectionSettings
packagesChildElement
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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.
MicrosoftEnterpriseLibrary5.0
CreatingaDatabaseObject
AlldataaccessmethodsareexecutedagainstaDatabaseobject.YoucanusetheEnterpriseLibrarycontainertocreateaDatabaseobject.ThespecifictypeofDatabaseobjectitreturnsisdeterminedbytheapplicationconfigurationinformation.Bychangingthedefaultconfiguration,theunmodifiedapplicationcanberunagainstdifferentdatabases.Theconnectionstringinformationforeachdatabaseyoudefineisstoredinthe<connectionStrings>sectionintheapplicationconfigurationfile.
Thistopicincludesthefollowingsectionsthatdescribehowtocreateinstancesofdifferenttypesofdatabases,andsomethingsyoumustconsiderwhenworkingwithspecifictypesofdatabases:
CreatingaDefaultDatabaseInstanceCreatingaNamedDatabaseInstanceCreatingaSpecificDatabaseTypeCreatingaDatabaseInstanceDirectlyCreatingaGenericDatabaseInstanceWritingCodetoUsetheDatabaseClassesUsingSQLServerCEUsingOraclewiththeTransactionScopeClassUsingtheOracleDataReaderWrapperClass
CreatingaDefaultDatabaseInstance
CreatingaNamedDatabaseInstance
CreatingaSpecificDatabaseType
CreatingaDatabaseInstanceDirectly
CreatingaGenericDatabaseInstance
WritingCodetoUsetheDatabaseClasses
UsingSQLServerCE
UsingOraclewiththeTransactionScopeClass
UsingtheOracleDataReaderWrapperClassToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
DbCommandObjectsforSQLStatements
DbCommandObjectsforStoredProceduresToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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)
'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#
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.
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
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.
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
Endversionofthemethodtoobtaintheresult.Yourcodewaitsuntilthemethodcompletes.However,youcanuseanarrayofthestandardWindowsWaitHandleclasstostartmultipledataaccessoperations,andthecodewillreturnwhentheyallcompleteortimeout.
Ifyouwanttoexecutecodeinyourapplicationwhilethedataaccesscallisexecuting,youcanusealambdaexpressionoraseparatecallbackthatisexecutedwhendataaccessiscomplete.Ifyouuseaseparatecallback,youpassareferencetoyourcallbackmethodtotheBeginmethod,andoptionallyanobjectcontainingstateinformationthatyouwanttomakeavailableinthecallbackmethod.AcommonuseofthisobjectistopassareferencetotheDatabaseobjectsothatyoucancalltheappropriateEndmethodinsidethecallbackhandler.Ifyouusealambdaexpression,itwillhaveaccesstotheobjects(suchastheDatabaseinstance)thatyouuseinthedataaccesscode.
AsthemethodsforperformingasynchronousexecutionmatchthoseavailablefortheADO.NETSqlClientclass,thefullrangeofoptionsandapproachestoperformingasynchronousdataaccessarenotincludedinthistopic.Formoreinformation,seeAsynchronousCommandExecutioninADO.NET2.0.
AsynchronousAccessorExecution
TipsforUsingtheAsynchronousDataAccessMethodsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ReturningDataasObjectsforClientSideQuerying
Developersoftenwanttoretrievedatainaformatthatbettermatchesthereal-worldobjectsthatthedatarepresents,ratherthanintherowsandcolumnsformatofaDataReaderorDataSet.ThisistypicallythecasewhenimplementingcommondesignpatternssuchasDomainModel,TableModule,andRepository.
TheDataAccessApplicationBlockincludessupportforthisscenariothroughaclasscalledanaccessor.Accessorsacceptinformationthatisrequiredtoextractthedata,andmappingsthatindicatehowtheinputparameterscorrespondtotheparametersoftheunderlyingquery.Theyuseoutputmappingsthatdefinehowthereturnedcolumnsmaptothepropertiesoftheobjectsthedeveloperwantstoworkwith,andreturnasequenceofobjectsofthespecifiedtype.Thefollowingschematicshowsthehighlevelprocesswhenusinganaccessortoretrievedataasanenumerablesequenceofobjects.
YoucanexecutebothstoredproceduresandSQLstatementsusingtheaccessorapproach.TheblockincludestheSprocAccessorclassforstoredprocedures
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.
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_
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.
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.
Afterthefirstcalltoastoredprocedurethatrequiresparameterdiscovery,theinformationabouteachparameterissavedintheparametercache.Thismeansthatsubsequentcallstothesamestoredprocedurewillnotrequirearound-triptothedatabase.
CreatingCustomParameterMappersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
BuildingOutputMappers
Anoutputmappertakestheresultsetreturnedfromadatabase(intheformofrowsandcolumns)andconvertsthedataintoasequenceofobjects.Therearetwodifferenttypesofoutputmappersthatyoucanusetotransformthereturneddata.Rowmapperstransformeachrowintoanobject,sothattheaccessorcanreturnasequenceoftheseobjects.Resultsetmapperstaketheentireresultsetandgenerateacompleteobjectgraphthatrepresentstheresultsetasobjects.
Thefollowingsectionsofthistopicprovidemoreinformationaboutthedefaultmappingcapabilitiesandthetwotypesofoutputmapper:
UsingtheDefaultRowMapperDefiningCustomRowMappingsCreatingResultSetMappers
Forinformationaboutusingoutputmapperswithanaccessor,seeCreatingandUsingAccessorsandExecutingQuerieswithoutCreatinganAccessor.
UsingtheDefaultRowMapper
DefiningCustomRowMappings
CreatingResultSetMappersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
ExecutingQuerieswithoutCreatinganAccessorExecutingAccessorQueriesAsynchronouslyAdditionalInformationforAccessorsandClient-sideQueries
StoredProcedureAccessor
SQLStringAccessor
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ExecutingQuerieswithoutCreatinganAccessor
Insteadofcreatinganaccessorfirst,andthenexecutingit,youcanusethemethodsoftheDatabaseclasstocreateanaccessorandexecuteitasoneoperation.YoucandothiswithboththeSprocAccessorandSqlStringAccessor.ThemaindifferencebetweenthisapproachandcallingtheExecutemethodexplicitlyonanexistingaccessoristhatyoumustalsopassanyrequiredparametersintotheExecuteSprocAccessormethod.Thefollowingsectionsshowthetechniqueforthetwotypesofaccessor:
StoredProcedureAccessorSQLStringAccessor
Seethefollowingtopicsformoreinformationaboutusingaccessorsinyourapplications:
DefiningParameterMappersBuildingOutputMappersCreatingandUsingAccessorsExecutingAccessorQueriesAsynchronouslyAdditionalInformationforAccessorsandClient-sideQueries
StoredProcedureAccessor
SQLStringAccessorToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
{
//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_
="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.
Note:Therearesomelimitationsonusingasynchronousdataoperations,andseveralissuesyoushouldbeawareof.Formoredetails,seeUsingtheAsynchronousDataAccessMethods.
Inaddition,whenyouexecuteanaccessorasynchronously,youcanonlyiterateovertheresultsetonce.Ifyouattempttoiterateoveritagain,theblockwillraiseanexception.Forthisreason,youmayneedtouseanapproachsuchastheToListmethodtoforcecompleteevaluationoftheresultsequence.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
AdditionalInformationforAccessorsandClient-sideQueries
Thistopicdescribessomeadditionalfactorsandissuesrelatedtousingaccessorstoretrievedataasasequenceofobjects.Itcoversthefollowing:
CreatingAccessorsthroughDependencyInjectionAccessingandIteratingtheResultsSetQueryingtheResultsSetUsingLINQDeferredLoadingandMultipleIterationsoftheResultSet
CreatingAccessorsthroughDependencyInjection
DeferredLoadingandMultipleIterationsoftheResultSetToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CreatingPortableDatabaseApplications
Thereareissuesthatyoumustconsiderifyourapplicationmustworkwithmultipledatabasetypes.
WorkingwithOracleDatabases
SuggestionsforCreatingPortableDatabaseApplicationsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
}
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
DimcmdAsDbCommand=db.GetStoredProcCommand("GetProductsByCategory")
UsingreaderAsIDataReader=db.ExecuteReader(cmd)
'Processresults
EndUsing
Fordesignandimplementationguidelinesforexceptionmanagementin.NET,seetheDesignGuidelinesforExceptions.
HandlingAsynchronousDataAccessExceptionsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
HandlingParameters
Moststoredproceduresacceptparameterswhosevaluesareeitherusedasinputtothestoredprocedureoraresetduringoutput.AswithADO.NET,theDataAccessApplicationBlockallowsdeveloperstoexplicitlyspecifyalloftheattributesofaparameter.Theseattributescanincludedirection,datatype,andlength.Thisapproachisnamedexplicitparameterhandling.However,asaconvenience,youcanspecifyonlythevalueswhenusinginputparameters.Inthiscase,theapplicationblockwilllookupandsupplytheparameterattributes.Thisapproachisnamedparameterdiscovery.
ExplicitParameterHandling
UsingColumnValuesasParameterInputs
ParameterDiscovery
OptionalParametersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
thedataaccessorsincludedintheblocktoretrievedataasasequenceofobjectsofaspecifiedtypefromthedatastore.PerformingAsynchronousDataAccess.ThisscenariodemonstrateshowyoucanusetheasynchronousversionoftheExecuteReadermethodtoreaddatafromadatastoreasynchronously,andthenaccesstheresultsusingacallbackthatindicateswhenthemethodcompletes.
ThistopichelpsyouimplementyourapproachbyusingtheDataAccessApplicationBlock.Itdoesnothelpyouchoosethecorrectapproachforyourparticularsituation(forexample,itdoesnothelpyouchoosebetweenaDataSetandaDbDataReader).Forguidanceonapproachestodataaccess,seethefollowingMicrosoftpatterns&practicesguides:
.NETDataAccessArchitectureGuideINFO:MicrosoftGuideforDesigningDataTierComponentsandPassingDataThroughTiersImproving.NETApplicationPerformanceandScalability
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingaDbDataReadertoRetrieveMultipleRows
Acommondatabasetaskistoretrieveanddisplayinformation.Forexample,anonlineretailapplicationmayneedtodisplayalistofproductswithinaspecifiedcategory.
TypicalGoals
Solution
UsingExecuteDataReader
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingaDataSettoRetrieveMultipleRows
Inamulti-tiersystem,youmayneedtopassdatafromadataaccesscomponenttoamiddle-tierbusinesscomponent.Thedataisretrievedfromthedatabaseandsentback,throughthedataaccesslayer,tothebusinesslayer.TheinformationiscontainedintheDataSetobject.
TypicalGoals
Solution
UsingExecuteDataSet
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ExecutingaCommandandAccessingOutputParameters
Acommondatabasetaskistoretrievespecific,multiple-columnvalues.Forexample,inaWeb-basedonlineretailapplication,youmaywanttoretrievefullproductdetailsforacertainproductinresponsetoauserrequest.
TypicalGoals
Solution
UsingExecuteNonQuery
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ExecutingaCommandandAccessingaSingleItemResult
Therearemanysituationsinwhichyouhavetoperformasingle-itemlookup.Forexample,anonlineretailermaywanttouseaproductIDtoretrieveaproductnameoruseacustomerIDtoretrieveacreditrating.
TypicalGoals
Solution
UsingExecuteScalar
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
PerformingMultipleUpdatesWithinaTransaction
Whenanapplicationexecutesmultipleoperationsagainstadatabase,acommonrequirementisthatalloftheoperationsmustsucceedorthedatabasemustrollbacktoitsoriginalstate(thatis,itsstatebeforetheoperationsbegan).Thisall-or-nothingrequirementisreferredtoasatransaction.Transactionsensuretheintegrityofadatabasesystem'sstate.Forexample,inaclassicbankingscenario,anapplicationmustdebitoneaccountandcreditanotherwithaparticularamountofmoney.Forproperaccounting,itisessentialthateitherbothoperationssucceedorneitheroperationsucceeds.Thismeansthatbothoperationsshouldbeperformedinthecontextofasingletransaction.
TypicalGoals
Solution
UsingExecuteNonQueryinaTransactionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingaDataSettoUpdateaDatabase
Databasesmustbeperiodicallyupdatedwithnewinformation.Forexample,inaWeb-basedonlineretailapplication,youmaywanttoaddanewcustomertothedatabase,modifythenameassociatedwithacustomerID,ordeleteacustomerrecordentirely.
TypicalGoals
Solution
UsingUpdateDataSet
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RetrievingMultipleRowsasXML
AnexampleofwhereyoumaywanttouseXMLdataiswithinane-commerceapplicationthatallowsclientstorequestaproductcatalogthatisinXMLformat.
TypicalGoals
Solution
UsingExecuteXmlReader
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RetrievingDataasObjects
Thisscenariodemonstratesoneofthewaysthatyoucanusethedataaccessorsprovidedwiththeblocktoreaddatafromadatastoreandreturnitasasequenceofobjectsofthetypeyouspecify.TheDataAccessApplicationBlockprovidestwotypesofaccessors,forstoredproceduresorforusewithSQLstatements,inadditiontoarangeofclassesthathelpyoutomapparameterstothequeryandmapthereturneddatatothetypeofobjectyourequire.Forinformationabouttheseclasses,seeReturningDataasObjectsforClientSideQuerying.
TypicalGoals
Solution
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
PerformingAsynchronousDataAccess
ThisscenariodemonstrateshowyoucanusetheasynchronousversionoftheExecuteReadermethodtoreaddatafromadatastoreasynchronously,andthenaccesstheresultsusingacallbackthatindicateswhenthemethodcompletes.YoudothisusingtheBeginExecutereaderandEndExecuteReadermethodsoftheDatabaseclass.
Note:AsynchronousdataaccessisnotsupportedbyallADO.NETdataproviders.TheDatabaseclassexposesaBooleanpropertynamedSupportsAsyncthatyoucantesttocheckatruntimeifasynchronousoperationsaresupported.Ifthispropertyreturnsfalse,anyasynchronousmethodsyoucallwillthrowanInvalidOperationException.InEnterpriseLibrary5.0,theonlydatabasetypethatsupportsasynchronousoperationistheSqlDatabaseclass.
TypicalGoals
UsingBeginExecuteReaderandEndExecuteReaderwithaCallback
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignoftheDataAccessApplicationBlock
TheDataAccessApplicationBlockincludesthefollowingfeatures:Asimpleandefficientwayofworkingwithdifferentdatabasesystems(seeDesigningforSimplifiedDataAccess)Awayofdevelopingdatabase-agnosticapplications(seeDesigningforDatabase-AgnosticApplications)Aneasywaytoadjustandvalidatethedatabaseconfigurationsettings
DesignGoals
DesignHighlightsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
DesignImplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesigningforDatabase-AgnosticApplications
TheDataAccessApplicationBlockprovidesanextensibleframeworkforsupportingmultipletypesofrelationaldatabases.Applicationsthatusetheapplicationblockareportableacrossdifferentdatabasesystems.
Thereareanumberofgeneraldataaccesstools—suchasOpenDatabaseConnectivity(ODBC)orOLEDB—thatcanprovideaccesstoavarietyofdatasources.Onedrawbacktothesetoolsisthathowtheyareuseddependsonthetargetdatabase.Thatmeansthatprogrammersneedtounderstandvariousprogrammingmodelstoaccessdifferentdatabasetypes.Movinganapplicationtoadifferentdatabasecouldrequireasignificantamountofrecoding.
AnotherdrawbacktotheODBCorOLEDBapproachisthatperformancemaysuffer.Genericdataprovidersareslowerthanthoseoptimizedforaparticulardatasource.TheDataAccessApplicationBlockprovidesanimplementationthatfeaturesbothportabilityandoptimizedperformance.
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
databasesystemshandlecommandsandparametersindifferentways.Database-derivedclassesprovidemethodsthatacceptparameterinformation;thespecificdatabasesystemsprovidetheirownderivedimplementationstohandleparameterparameters.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
MicrosoftEnterpriseLibrary5.0
AddingaNewApplicationBlockDatabaseProvider
Iftherelationaldatabasesystemyouareusingdoesnotalreadyhaveanapplicationblockdatabaseprovider,youcancreateyourown.Thisisonlynecessaryiftheapplicationblock'sGenericDatabaseclassdoesnotmeettherequirementsofyourapplication.(ThisassumesthatthereisanADO.NETDbProviderFactorytypeforthedatabasesystemyouareusing.)Tocreateanewdatabaseprovider,youmustcreateanewdatabaseclassthatderivesfromtheDatabaseclass.Additionally,ifyouwantyourclientcodetoremaindatabase-agnostic,youmighthavetowriteadditionalcodetoperformsuchtasksastypeconversion.
CreatingaNewDatabaseClass
ConfiguringYourApplicationtoUsetheNewProvider
RecommendationsforCreatingaDatabaseProviderToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetoseethattheinitialdeploymentoftheDataAccessApplicationBlockisplannedandmanagedandthatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheapplicationblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheapplicationblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheapplicationblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheDataAccessApplicationBlock,seethefollowingtopics:
DataAccessApplicationBlockPerformanceCountersDataAccessApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DataAccessApplicationBlockEventLogEntries
TheDataAccessApplicationBlockisinstrumentedtologentriestotheapplicationeventlogforavarietyofevents.ThistopicliststheDataAccessApplicationBlockeventlogentries.
ConnectionFailedEvent
CommandExecutedEvent
CommandFailedEvent
DataConfigurationFailureEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
WhenShouldIUsetheExceptionHandlingApplicationBlock?Thistopicwillhelpyoutodecideiftheblockissuitableforyourrequirements.Itexplainsthebenefitsofusingtheblock,andanyalternativetechniquesyoumayconsider.Italsoprovidesdetailsofanylimitationsoftheblockthatmayaffectyourdecisiontouseit.DevelopingApplicationsUsingtheExceptionHandlingApplicationBlock.ThistopicexplainshowtoconfiguretheExceptionHandlingApplicationBlock,howtoaddtheblocktoyourapplications,howtodetermineappropriateexceptionhandlingpolicies,howtospecifydifferenthandlingactions,andhowtosendanexceptiontotheExceptionHandlingBlock.KeyScenarios.ThistopicshowsdifferentwaystousetheExceptionHandlingApplicationBlockinyourownapplications.DesignoftheExceptionHandlingApplicationBlock.Thistopicexplainsthedecisionsthatwentintodesigningtheblockandtherationalebehindthosedecisions.ExtendingandModifyingtheExceptionHandlingApplicationBlock.Thistopicexplainshowtoextendtheapplicationblockbyaddingcustomhandlersandformatters.Italsogivessomeadviceabouthowtomodifythesourcecode.DeploymentandOperations.Thistopicexplainshowtodeployandupdatetheblockassemblies.
MoreInformationFormoreinformation,seethefollowingMicrosoft®patterns&practicesguides:
ApplicationArchitecturefor.NET:DesigningApplicationsandServicesDesignGuidelinesforExceptions
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
particularexceptiontype.Exceptionhandlersare.NETclassesthatencapsulateexceptionhandlinglogicandimplementtheExceptionHandlingApplicationBlockinterfacenamedIExceptionHandler.
Youcanchainthesehandlerstogethersothataseriesofthemexecutewhentheassociatedexceptiontypeishandled.Thefollowingaresomeexamplesofnamedpoliciesanddescriptionsofwhattheymightprovide:
Basepolicy.Thispolicylogstheexceptionandre-throwstheoriginalexception.Securepolicy.Thispolicylogstheexception,replacestheoriginalexceptionwithacustomexception,andthrowsthenewexception.Expressivepolicy.Thispolicywrapstheoriginalexceptioninsideanotherexceptionandthrowsthenewexception.
Thefollowingschematicillustratesexamplesofcross-layerandsingle-applicationcomponentexceptionhandling.
Figure1Examplesofexceptionhandlingpolicies
Inthisexample,exceptionsthatoccurinthedataaccesslayerareloggedandthenwrappedinsideanotherexceptionthatprovidesmoremeaningfulinformationtothecallinglayer.Withinthebusinesscomponentlayer,theexceptionsareloggedbeforetheyarepropagated.Anyexceptionsthatoccurinthebusinesscomponentlayerandthatcontainsensitiveinformationarereplacedwithexceptionsthatnolongercontainthisinformation.Thesearesenttotheuserinterface(UI)layeranddisplayedtotheuser.
Forinformationabouthowtodevelopexceptionmanagementstrategies,seeDeterminingAppropriateExceptionPoliciesandActions.
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
ScenariosfortheExceptionHandlingBlock
BenefitsoftheExceptionHandlingApplicationBlock
LimitationsoftheExceptionHandlingApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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
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
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
exceptionhandlers.
ConfiguringExceptionHandlersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
exceptionHandlingElement
exceptionPoliciesChildElement
exceptionTypesChildElement
exceptionHandlersChildElement
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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;
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.
MicrosoftEnterpriseLibrary5.0
DeterminingAppropriateExceptionPoliciesandActions
Thisinformationprovidesanoverviewofmanagingexceptionsinyourapplications.Forcompletedesignandimplementationguidelinesforcreatingexceptionmanagementsystemsthatuse.NETtechnologies,seeDesignGuidelinesforExceptionsonMSDN®.
Tobuildsuccessfulandflexibleapplicationsthatcanbemaintainedandsupportedeasily,youmustuseanappropriatestrategyforexceptionmanagement.Youmustdesignyoursystemtomakesurethatitcandothefollowing:
DetectexceptionsLogandreportinformation
Thefollowingtopicsprovideusefuladviceabouthowyoushoulddevelopyourexceptionmanagementstrategies:
GenerateEventsThatCanBeMonitoredExternallytoHelpSystemOperationExceptionHandlingProcessandtheExceptionHandlingApplicationBlockWhentoCatchExceptionsExceptionPropagationHidingExceptionInformationExceptionNotificationPlanningforExceptionHandling
GenerateEventsThatCanBeMonitoredExternallytoHelpSystemOperation
ExceptionHandlingProcessandtheExceptionHandlingApplicationBlock
WhentoCatchExceptions
ExceptionPropagation
HidingExceptionInformation
ExceptionNotification
PlanningforExceptionHandlingToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
SpecifyingDifferentHandlingActionsBasedonExceptionTypeandPolicy
TheExceptionHandlingApplicationBlockseparatesthedefinitionofhowanexceptionshouldbeprocessed(whichistheexceptionpolicy)fromtheapplicationcodethatusestheblocktohandleexceptions.Youusetheconfigurationtoolstocreateandnamepolicies.
Byusingexceptionpolicies,theapplicationbehaviorthatoccursinresponsetoanexceptioncanbemodifiedwithoutchangingtheapplicationcode.
ConfiguringExceptionPolicies
ConfiguringExceptionTypes
UnderstandingExceptionHandlersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
SendinganExceptiontotheExceptionHandlingApplicationBlock
InteractionbetweenapplicationcodeandtheExceptionHandlingApplicationBlockoccurswhentheapplicationcodecatchesanexceptionandsendsittotheblocktobehandled.Applicationdevelopersdonothavetoknowhowexceptionswillbehandledbecausetheyhavetospecifyonlythenameoftherelevantexceptionpolicy.
Therearethreemainscenariosinwhichyoumayneedtohandleexceptions.Themostcommonisthefirstofthese,butthistopicexplainshowyoucanusetheblocktoimplementallthreescenarios.Thescenariosare:
HandlingAllExceptionsinaCatchSectionHandlingSpecificExceptionsinaCatchSectionExecutingCodeBeforeorAfterHandlinganException
HandlingAllExceptionsinaCatchSection
HandlingSpecificExceptionsinaCatchSection
ExecutingCodeBeforeorAfterHandlinganExceptionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
HandlingandThrowingExceptions
Whenanexceptionoccurs,itpassesupthestackandeachcatchblockcanpotentiallyhandleit.Theorderofcatchstatementsisimportant.Putcatchblocksthattargetspecificexceptionsbeforeageneralcatchblock.Otherwise,thecompilermightissueanerror.Thecommonlanguageruntime(CLR)determinesthepropercatchblockbymatchingthetypeoftheexceptiontothenameoftheexceptionspecifiedinthecatchblock.Ifthereisnospecificcatchblock,ageneralcatchblock,ifitexists,handlestheexception.
DebuggingandExceptionPropagation
HandlingSpecificExceptions
User-FilteredExceptionsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
ExceptionsThatOccurDuringExceptionHandlingToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LogginganException
Afrequentlyrequiredexception-handlingtaskistologtheinformationassociatedwiththeexception.TheExceptionHandlingApplicationBlock,inconjunctionwiththeLoggingApplicationBlock,letsyoulogformattedexceptioninformationinlocationsspecifiedintheconfigurationfile.Forexample,clientapplicationstypicallylogapplicationinformationintheeventlog,whileaservercomponentofane-commerceapplicationmaylogexceptionsinadatabase.
TypicalGoals
Solution
UsingtheLoggingHandler
ModifyYourApplication
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ReplacinganException
Afrequentlyrequiredexception-handlingtaskistoreplacetheoriginalexceptionwithanotherexception.Forexample,ifanexceptionisgoingtocrossatrustboundary,youmaynotwanttosendtheoriginalexceptionbecauseitcontainssensitiveinformation.
TypicalGoals
Solution
UsingtheReplaceHandler
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
TypicalGoals
Solution
UsingtheWrapHandler
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
PropagatinganException
Afrequentlyrequiredexception-handlingtaskistoallowtheoriginalexceptiontopropagateupthecallstackunchanged.Youmaywanttodothisbecausethehandlersonlyperformactionssuchasloggingthatleavetheexceptionunchangedorbecauseotheractions,suchaswrappingandreplacing,havebeenturnedoff.Forexample,aroutinewithinabusinesslogiccomponentmaylogexceptionsatthepointwheretheyaredetected.Itthenpropagatesthatexceptiontothecallerforadditionalhandling.
TypicalGoals
Solution
PropagatinganException
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DisplayingUser-FriendlyMessages
Youmaywanttoreplacethemessageintheoriginalexceptionwithamoreappropriate,user-friendlymessage.Todothis,youmustreplacetheoriginalexceptionwithanotherexceptionthathasamoreappropriatemessageassociatedwithit.Forexample,exceptionsthatoccurinthedataaccesslayerofanapplicationcanbereplacedwithanexceptionoftypeSystem.ApplicationException.Thisusesthemessage,"Theapplicationisunabletoprocessyourrequestatthistime."Thismessageisthendisplayedtotheuser.
TypicalGoals
Solution
DisplayingUser-FriendlyMessagesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
NotifyingtheUser
WhenyouusetheExceptionHandlingApplicationBlock,afrequentlyrequiredtaskistonotifytheuserwhenanexceptionoccurs.(Generally,thisshouldbecompletedafterthemessagehasbeenchangedtoonethatissuitablefortheparticularuser.Formoreinformation,seeDisplayingUser-FriendlyMessages.)Dependingontheapplicationtype,youcandothisusingaWindowsFormsdialogboxoraWebpage.Whenanexceptioncannotbehandledwithintheapplication,theusermustreceiveanotificationthatanerroroccurred,alongwithsomeguidanceofwhatheorsheshoulddonext.
TypicalGoals
Solution
NotifyingtheUser
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
AssistingSupportStaff
WhenyouusetheExceptionHandlingApplicationBlock,afrequentlyrequiredtaskistoallowsupportstafftoaccessdetailedinformationtoassistuserswhenexceptionsoccur.Whenanexceptionoccursthatcannotbehandled,usersaregenerallyshownafriendlyerrormessage.Usersmayhavetocallsupportstaff,andsupportstaffmayneedmorethantheusererrormessagetodeterminewhatwentwrongandhowtofixtheproblem.Thisscenariodemonstrateshowtomatchtheuser'serrormessagewiththedetailedexceptionlogthatcanbeaccessedbysupportstaff.
TypicalGoals
Solution
AssistingSupportStaff
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
TheExceptionHandlingApplicationBlockincludessupportforexceptionshieldingatWCFserviceboundaries.Thissupportconsistsofthefollowing:
TheExceptionShieldingAttribute,whichisusedtoassociateanamedexceptionhandingpolicyconfiguredintheExceptionHandlingApplicationBlockwithaWCFserviceoperation.Formoreinformation,seethefollowingsectionUsingtheExceptionShieldingAttribute.TheFaultContractExceptionHandler,whichconvertsanexceptiontoaspecifictypeofFaultContractandmapsthedesiredpropertiesoftheexceptiontotheFaultContract.Formoreinformation,seethefollowingsectionUsingtheFaultContractExceptionHandler.
UsingtheExceptionShieldingAttribute
UsingtheFaultContractExceptionHandlerToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignoftheExceptionHandlingApplicationBlock
TheExceptionHandlingApplicationBlockisdesignedtoachievethefollowinggoals:
Encapsulatethelogicusedtoperformthemostcommonexceptionhandlingtasksintominimalapplicationcode.Relievedevelopersoftherequirementtowriteduplicatecodeandcustomcodeforcommonexceptionhandlingtasks.Allowexceptionhandlingpoliciestobechangedaftertheyhavebeendeployedandtoensurethatchangeshappensimultaneouslyandconsistently.Incorporatebestpracticesforexceptionhandling,asdescribedintheDesignGuidelinesforExceptions.
DesignHighlightsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesigningforSimplifiedCatchBlocks
Commonexceptionhandlingbehavior,suchasloggingandreplacingexceptionstohidesensitiveinformation,typicallyrequiresmultiplelinesofcode.Updatingexception-handlingbehaviortoaccommodateachangeinanexceptionhandlingpolicyusuallyinvolvesupdatingmultiplefilesandlinesofcode.Thisprocesscanbeerror-prone,anditisdifficulttoensurethatpoliciesareupdatedconsistentlyacrossalllayersofanapplication.
TheExceptionHandlingApplicationBlocksimplifiesboththeexceptionhandlingcodeandtheprocessofupdatingthatcode.Itdoesthisbyassociatingexception-handlingbehaviorwithpolicynamessuchasDataAccessLayerPolicyandTrustBoundaryPolicy.Thebehaviorsrepresentedbypolicynamesarecontrolledexternally,intheconfigurationfortheapplication.Thismeansthatadeveloperneedstouseonlytwoelementstowritecodeinthecatchblockofanapplication:
AcalltotheHandleExceptionorProcessmethodthatpassesthepolicynameandtheexception.AcheckofthereturncodefromtheHandleExceptionmethod;ifitreturnstrue,theoriginalexceptionshouldbere-thrown.
DesignImplications
APISupportforPolicyNamesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesigningforEncapsulationofBehaviorinReusableHandlers
TheExceptionHandlingApplicationBlockhelpsdeveloperstocreateexceptionhandlersthatrepresentcommonexceptionhandlingtasks.Thesehandlers,aswellascombinationsofhandlers,canbeusedbydifferentpolicies.
DesignImplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
AddingaNewExceptionHandler
Toaddanewexceptionhandler,youmustfirstcreateanewclassthatimplementstheIExceptionHandlerinterface.Afteryoucompilethenewclassintoanassembly,youcanusetheEnterpriseLibraryConfigurationConsoletoaddittotheExceptionHandlingApplicationBlockconfigurationforyourapplication.
CreatingaNewExceptionHandlerClassToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
Note:IfyouhavecustomformattersdesignedforusewithversionsofEnterpriseLibrarypriortoversion4.1,youmustupdatethemsothatthehandlinginstanceIDisnotlost.
CreatingaNewExceptionFormatterClassToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetomakesurethattheinitialdeploymentoftheExceptionHandlingApplicationBlockisplannedandmanagedandtomakesurethatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecideiftheywishtousetheinstrumentationexposedbytheblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheExceptionHandlingApplicationBlock,seethefollowingtopics:
ExceptionHandlingApplicationBlockPerformanceCountersExceptionHandlingApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
MicrosoftEnterpriseLibrary5.0
ExceptionHandlingApplicationBlockEventLogEntries
TheExceptionHandlingApplicationBlockisinstrumentedtologentriestotheapplicationeventlogforavarietyofevents.ThistopicliststheExceptionHandlingApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
ExceptionHandlingErrorEvent
ConfigurationErrorEvent
InternalErrorEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
applications.Itshowshowtoconfiguretheapplicationblocktoperformcommontasksandhowtoaddapplicationcodetotheapplicationblockwhererequired.KeyScenarios.Thistopicdemonstrateshowtousetheapplicationblocktoperformthemostcommonloggingoperations.DesignoftheLoggingApplicationBlock.Thistopicexplainsthedecisionsthatwentintodesigningtheapplicationblockandtherationalebehindthosedecisions.ExtendingandModifyingtheLoggingApplicationBlock.Thistopicexplainshowtoextendtheapplicationblockbycreatingyourowncustomtracelisteners,logformatters,andlogfilters;andexplainshowtomodifythesourcecode.DeploymentandOperations.Thistopicexplainshowtodeployandupdatetheapplicationblock'sassembliesandalsocontainsinformationabouttheinstrumentationintheblock.
MoreInformationFormoreinformationaboutloggingandmanagingothercrosscuttingconcerns,seethefollowingpatterns&practicesguides:
MicrosoftApplicationArchitectureGuide,2ndEditionDesignGuidelinesforExceptions
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhatDoestheLoggingBlockDo?
Althoughtheprocessofcreatingandwritinglogentriesisrelativelysimple,thenumberofoptionsavailable(suchasthemanyloggingtargetsandtheabilitytofilterentries)meansthattheunderlyingstructureoftheblockandtheoptionsavailableforusingitcanseemcomplex.Thefollowingschematicshowshowthemaintypesofobjectintheblockworktogethertoprovideflexibilitywhencreatingandwritinglogentries.
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
entrytozero,one,ormoretargets(suchassendingitase-mailaswellaswritingittotheWindowsEventLog).LogFormatters.Eachtracelisteneryouaddtoyourconfigurationcanusealogformattertoconvertthedatainthelogentryfromaseriesofpropertiesintoformatsuitableforsendingtothelogtarget.Theblockcontainsatextformatterthatyoucanconfigurewithtracelistenersthatdispatchlogentriestotargetssuchasdiskfiles,e-mail,orWindowsEventLog;andabinaryformatterthatserializesthelogentrydataintoaformatsuitablefortransmissiontotargetssuchasWindowsMessageQueuing(MSMQ).Thetextformatterisconfigurablesothatyoucanmodifytheformatandcontentofthetextmessage,includingusingplaceholdersforthevaluesofthepropertiesofthelogentry.
TheLoggingProcessSequence
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheLoggingBlock?
IfyourapplicationshavearequirementtologinformationtoWindowsEventLog,e-mail,adatabase,amessagequeue,WindowsManagementInstrumentation(WMI),orafile,youshouldconsiderusingtheLoggingApplicationBlocktoprovidethisfunctionality.Inparticular,theLoggingApplicationBlockisusefulifyouneedtofilterloggingmessagesbasedoncategoryorpriority,ifyouneedtoformatthemessages,orifyouneedtochangethedestinationofthemessagewithoutchangingtheapplicationcode.TheLoggingApplicationBlockisalsodesignedtobeextensibleandincludesthefacilitytocreatecustomformattersandtracelisteners,whichyoucanadapttomeetyourapplication'sloggingrequirements.
ScenariosfortheLoggingApplicationBlock
BenefitsoftheLoggingApplicationBlock
LimitationsoftheLoggingApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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
ConfiguringTraceSourceCategoriesConfiguringLoggingFiltersConfiguringtheApplicationBlock
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ConfigurationOverview
TounderstandhowyouconfigureandusetheLoggingApplicationBlock,youmustbefamiliarwiththewaytheblockprocesseslogentries.ThetopicWhatDoestheLoggingBlockDo?providesasimplifiedoverviewoftheprocessandwillhelpyouwhenyoucometoconfiguretheblock.
ThefollowingstepsillustratethegeneralprocessforconfiguringtheLoggingApplicationBlock.ItassumesyouwanttousetwocategoriesnamedDevandOperations.
1. AddthetracelistenersyouwanttousetooutputthelogginginformationbyclickingontheplussigniconintheLoggingTargetListenerssectionoftheLoggingSettingsconfigurationpaneandclickingAddLoggingTargetListenerstodisplaythelistoflisteners.Whenyouselectalistener,itisaddedtotheLoggingTargetListenerssectionwhereyoucanthensetitsproperties.
2. AddtheformattersyouwantthetracelistenerstousetoformattheoutputbyclickingontheplussigniconintheLogMessageFormatterssectionoftheLoggingSettingsconfigurationpaneandclickingAddLogMessageFormatterstodisplaythelistofformatters.Whenyouselectaformatter,itisaddedtotheLogMessageFormatterssectionwhereyoucanthensetitsproperties.
3. SettheFormatterNamepropertyofeachtracelistenerintheLoggingTargetListenerssectionoftheLoggingSettingsconfigurationpanetospecifytheappropriateformatter.
4. AddthecategoryfiltersyouwanttousetotheCategoriessectionoftheLoggingSettingsconfigurationpanebyclickingontheplussigniconintheCategoriessectionoftheLoggingSettingsconfigurationpaneandclickingAddCategory.AnewcategoryitemisaddedtotheCategoriessectionwhereyoucanthensetitsproperties.Clickonitspropertyexpanderarrowifthepropertiesarenotvisible.
5. AddareferencetoeachofthetracelistenersyouwanttousetooutputthelogginginformationtoeachofthecategoriesyoucreatedintheCategoriessectionoftheLoggingSettingsconfigurationbyclickingtheListenerspropertyplussigniconandselectingaconfiguredloggingtargetlistener.EachentryhereisareferencetooneofthetracelistenersyoupreviouslyconfiguredintheTraceListenerssection.Youcanaddmorethanonetracelistenerreferencetoeachcategoryfilteryoucreate.Forexample,youcouldspecifythefollowing:
AlogentrycontainingthecategorynameDevwillgotoaneventlogtracelistener(sothatitappearsinWindowsEventLog)AlogentrycontainingthecategorynameOperationswillgotoane-mailtracelistenerandtoanXMLtracelistener.
6. AddareferencetoeachofthetracelistenersyouwanttousetooutputthelogginginformationtotheappropriatesubsectionsoftheSpecialCategoriessectionoftheLoggingSettingsconfigurationpane.Forexample,youmaywanttodothefollowing:
Sendthelogentrytoane-mailtracelistenerwhenanerroroccurswithintheloggingsystembyaddingareferencetothistracelistenertotheLoggingErrors&Warningssection.Sendthelogentrytoaneventlogtracelistenerwhenthelogentrydoesnotmatchanyconfiguredcategorybyaddinga
referencetothistracelistenertotheUnprocessedCategorysection.Sendalllogentries,irrespectiveofcategoryorcontent,toaFlatFiletracelistenerbyaddingareferencetothistracelistenertotheAllEventssection.
7. Settheremainingpropertiesforeachcategoryorspecialfilter.Specifythelogginglevel,suchasCritical,Error,Warning,orAll,bysettingtheMinimumSeveritypropertyforeachcategoryfilter.
8. Finally,addanylogfiltersyouwanttousetotheLoggingFilterssectionoftheLoggingSettingsconfigurationpanebyclickingontheplussigniconintheLoggingFilterssectionoftheLoggingSettingsconfigurationpaneandclickingAddLoggingFilters.ThefiltertypeyouselectisaddedtotheLoggingFilterssectionwhereyoucanthensetitsproperties.Clickonitspropertyexpanderarrowifthepropertiesarenotvisible.Forexample,youcoulduseacategoryfiltertoblockallloggingoperationsexceptthosethatspecifyoneofthetwocategoriesnamedDevorOperations.
ForspecificdetailsofhowtoconfigureeachsectionoftheLoggingApplicationBlockconfiguration,seeEnteringConfigurationInformation.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ConfiguringTraceListeners
Tracelistenersreceivelogentriesandwritethemtotheappropriatedestinations.ThefollowingproceduredescribeshowtoconfigurethetracelistenerssuppliedwithEnterpriseLibraryandcustomtracelistenersthatyoucreate.ThereisalsoaspecificprocedureforconfiguringthetwotracelistenersthatarerequiredforintegrationwithWCF.Formoredetailsofthisprocedure,seeConfiguringWCFIntegrationTraceListeners.
Note:Tracelistenerlogshavevulnerabilitiesandshouldbeprotectedasappropriate,dependingonwhetherthetracelistenerwriteslogentriestoafile,databaseorMSMQmessagequeue.
Fortracelistenersthatwritelogentriestofilesyoushouldprotectthelogsbyusingaccesscontrollists.ThisincludesFlatFile,Rollingflatfile,WMIandXMLtracelistenerlogs.
Fortracelistenersthatwritelogentriestodatabasesyoushouldprotectaccesstologsbyusingusernamesandpasswords.Thisincludesthedatabasetracelistener.
FortracelistenersthatwritelogentriestoMSMQmessagequeuesyoushouldallowonlyauthorizeduserstoreadinformationfromMSMQ.ProtectthequeuewithrelevantaccesscontrollistsandfollowanysecurityconsiderationsspecifictoMSMQ.Thisincludesthemessagequeuingtracelistener.
ConfiguringtheBuilt-inTraceListeners
ConfiguringCustomTraceListenersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
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.
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.
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:
IfthefileyouspecifyfortheFlatFileTraceListenerisread-only,thetracelistenerdoesnotwritethedatatothefileandnoexceptionoccurs.Makesurethatthefileattributesaresettoread/write.
WhenyouusetheFlatFileTraceListenerclasstowriteloginformationtoafile,theblocklocksthefileuntiltheapplicationcloses.Itispossibletoopenandreadthefile,butyoucannotmoveordeletethelogfileuntilyouclosetheapplication.
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.
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.
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.
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
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.
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.
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.
Note:IfyouspecifyaSystemDiagnosticstracelistenerthatwritestoafileandthatfileisread-only,thetracelistenerdoesnotwritethedatatothefileandnoexceptionoccurs.Makesurethefileattributesaresettoread/write.
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.
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.
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.
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
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.
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"
name="XMLTraceListener"/>
</listeners>
<formatters>
</formatters>
<categorySources>
<addswitchValue="All"name="System.ServiceModel">
<listeners>
<addname="XMLTraceListener"/>
</listeners>
</add>
</categorySources>
<specialSources>
<allEventsswitchValue="All"name="AllEvents"/>
<notProcessedswitchValue="All"name="UnprocessedCategory"/>
<errorsswitchValue="All"name="LoggingErrors&Warnings"/>
</specialSources>
</loggingConfiguration>
<system.serviceModel>
<diagnostics>
<messageLogginglogEntireMessage="true"
logMalformedMessages="true"
logMessagesAtTransportLevel="true"/>
</diagnostics>
<services>
<servicename="WCFServiceLibrary1.service1"
behaviorConfiguration="MyServiceTypeBehaviors">
<endpointcontract="WCFServiceLibrary1.IService1"
binding="wsHttpBinding"/>
<endpointcontract="IMetadataExchange"binding="mexHttpBinding"
address="mex"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behaviorname="MyServiceTypeBehaviors">
<serviceMetadatahttpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</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.
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.
TextFormatterTemplateTokensToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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).
ConfiguringTraceSourceCategories
ConfiguringTraceSourcesSpecialCategory
SourceCategoryProperties
Severity(SourceLevels)ValuesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
CategoryFilterProperties
LoggingEnabledFilterProperties
PriorityFilterProperties
CustomLoggingFilterPropertiesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
LoggingApplicationBlockProperties
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
loggingConfigurationElement
logFiltersChildElement
categoryFiltersChildElement
categorySourcesChildElement
listenersChildElement(categorySources)
specialSourcesChildElement
listenersChildElement(errors)
notProcessedChildElement
listenersChildElement(notProcessed)
allEventsChildElement
listenersChildElement(allEvents)
listenersChildElement(loggingConfiguration)
formattersChildElement
msmqDistributorSettingsElement
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
EachinstanceoftheLoggingApplicationBlockusesaninstanceofthemessagequeuingtracelistener(theMsmqTraceListenerclass)tosendthelogentriestoasingledestinationqueue.ThedistributorservicepollsthequeueandusesanotherinstanceoftheLoggingApplicationBlocktodirectthelogentriestothepropertracelisteners.Notethatthedistributorservicecanrunonaremotecomputer.Thefollowingsectionsdescribeinstallingandusingthedistributorservice:
InstallingtheDistributorServiceStartingtheDistributorServiceUnderstandingtheserviceNameAttribute
InstallingtheDistributorService
StartingtheDistributorService
UnderstandingtheserviceNameAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
Note:ItisalsoagoodideatoaddareferencetotheMicrosoft.Practices.EnterpriseLibrary.Logging.Database.dlltoyourprojectsothattheassemblyrequiredatruntimeiscopiedtotheoutputfolder.
4. Addtheapplicationcode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
CheckingFilterStatusbeforeConstructingLogMessages.Thisscenarioillustrateshowtoavoidcollectingloginformationformessagesthatwillnotbeloggedaccordingtothecurrentconfigurationinformation.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LoggingtoaDatabase
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.Itdescribestheprocessforsettinguptheblocktosendlogeventstoadatabase.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasareferencetohelpyouquicklysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
TypicalGoals
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LoggingtoWindowsEventLog
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.ItdescribestheprocessforsettinguptheblocktosendlogeventstoWindowsEventLog.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasaquickreferencetohelpyourapidlysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
TypicalGoals
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LoggingtoaDiskFile
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.Itdescribestheprocessforsettinguptheblocktosendlogeventstoadiskfile.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasaquickreferencetohelpyouquicklysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
TypicalGoals
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LoggingtoWindowsMessageQueuing
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.ItdescribestheprocessforsettinguptheblocktosendlogeventsasmessagesthroughWindowsMessageQueuing.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasaquickreferencetohelpyouquicklysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
TypicalGoals
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LoggingtoWMI
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.ItdescribestheprocessforsettinguptheblocktosendlogeventstotheWindowsManagementInstrumentationdatabase.Theprocessjustinvolvesconfiguringtheblock—therearenoothertasksrequiredtoprepareyourapplication.ThistopicactsasaquickreferencetohelpyouquicklysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
TypicalGoals
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LoggingasE-mailMessages
ThisscenarioisoneofseveralthatdescribethetypicalrequirementswhenusingtheLoggingApplicationBlockinyourapplications.Itdescribestheprocessforsettinguptheblocktosendlogeventsase-mailmessages.Theprocessinvolvesconfiguringtheblockandperformingothertaskstoprepareyourapplication.ThistopicactsasaquickreferencetohelpyourapidlysetuptheLoggingApplicationBlocktoperformtherequiredloggingaction.
TypicalGoals
SolutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
PopulatingandRaisingEventsfromCode
TheabilitytopopulateandraiseeventsfromcodeisfundamentaltothefunctionalityoftheLoggingApplicationBlock.
TypicalGoals
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
PopulatingaLogMessagewithAdditionalContextInformation
TheLogEntryclassdefinespropertiestoholdinformationcommontotypicalloggingscenarios.Developersoftenneedtoaddcontextinformationtologentries.Thesametypeofcontextinformationcanberequiredformultiplelogentriesinthesameapplicationorinmultipleapplications.Becausecontextinformationcanbeexpensivetogather,certaintypesofinformationarenotautomaticallycollected.TheExtraInformationprovidersgathercontextinformationthatisusefulbutnotalwaysnecessarybecauseitisexpensivetocollect.ExamplesarestacktraceinformationandCOM+information.
TypicalGoals
Solution
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TracingActivitiesandPropagatingContextInformation
Insomecases,youwillneedtologinformationatthestartandendofaparticularactivity,includingtiminginformation.Inaddition,youcantracetheprogressoftheactivityatselectedpointsintheapplication.TracingallowsyoutoassociatealleventsbetweenthestartandendofanactivitywithanActivityIDpropertyandacategory.TheActivityIDpropertyallowsyoutocorrelatelogentriesthatarewrittenduringtheexecutionofanactivity.Youcanusefiltersandcategoriestodirectandcontroltheinformationproducedforaneventthatcanoccurinthecontextofanyactivity.
TypicalGoals
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CheckingFilterStatusbeforeConstructingLogMessages
ByusingtheLoggingApplicationBlock,youcanquerythefilterstatustodeterminewhetheralogmessageshouldbeloggedaccordingtothefilterconfiguration.
TypicalGoals
Solution
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignoftheLoggingApplicationBlock
TheLoggingApplicationBlockincludesthefollowingfeatures:AsimpleandconsistentwayofloggingeventinformationDistributionofinformationtomultiplesourcesActivitytracingtomarkthestartandendofanactivitysuchasausecaseSimplifiedapplicationblockconfigurationusingtheconfigurationtoolsExtensibilitythroughcustomtracelistenersandformatters
DesignGoals
DesignHighlights
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesigningforSimpleandConsistentLoggingFunctionality
Developersfacemanyimplementationchoicesandrequirementswhentheyaddloggingfunctionalitytotheirapplications.Differentapplicationsmayloginformationtodifferentdestinations.Forexample,oneapplicationmayuseaneventlogandanotherapplicationmayuseaflatfile.Evenasingleapplicationmayloginformationtomultipledestinations.Asaresult,developersmustoftenwriteduplicatecodeforcommontaskssuchaswritingtoaneventlogortoaflatfile.
Uniformimplementationsmakethecodeeasiertounderstand,morepredictable,andeasiertomaintain.However,differentdevelopmentteamsroutinelyimplementdifferentloggingstrategies.TheLoggingApplicationBlockencapsulatesthelogicthatperformsloggingandtracingoperationsintoafewclassesthathavesmallnumbersofmethods.Thesemethodsarethesameforalllogmessagedestinations.ThismeansthatapplicationsthatusetheLoggingApplicationBlockareconsistentinthewaysthattheyloginformation.ByusingtheLoggingApplicationBlock,thisconsistencyremainsacrosssingleprojects,multipleprojects,orenterprise-scalesolutions.
DesignImplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
Specifyanycustomconfigurationpropertiesbymodifyingtheattributesoftheobject.
CreatingaCustomLogEntryFormatter
CreatingaCustomTraceListener
CreatingaCustomLogFilterToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetoseethattheinitialdeploymentoftheLoggingApplicationBlockisplannedandmanagedandthatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheapplicationblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheapplicationblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheapplicationblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedintheLoggingApplicationBlock,seethefollowingtopics:
LoggingApplicationBlockPerformanceCountersLoggingApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
LoggingApplicationBlockEventLogEntries
ThistopicliststheLoggingApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
FailureLoggingErrorEvent
LockAcquisitionErrorEvent
ConfigurationFailureEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
decisionsthatwentintodesigningtheSecurityApplicationBlockandtherationalebehindthosedecisions.ExtendingandModifyingtheSecurityApplicationBlock.Thistopicexplainshowtoextendtheblockbycreatingyourownprovidersandhowtomodifythesourcecode.DeploymentandOperations.ThistopicexplainshowtodeployandupdatetheSecurityApplicationBlock'sassembliesandalsocontainsinformationaboutconfiguration.
MoreInformationFormoreinformation,seethefollowingpatterns&practicesguides:
ApplicationArchitecturefor.NET:DesigningApplicationsandServices.NETDataAccessArchitectureGuideDesignGuidelinesforExceptions
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhatDoestheSecurityApplicationBlockDo?
TheSecurityApplicationBlockallowsyoutoperformtwoseparatebutrelatedtasks.Youcanauthorizeusersagainstarangeofauthorizationproviders,and/orcacheauser'sidentityandsecuritycontextforusethroughoutyourapplication.Thecoderequiredtousethesefeaturesissimple,andtheactualmechanicsofaccessingauthorizationsystemsandcachingidentitiesandsecuritycontextsareabstractedwithintheblock.Often,youonlyneedtowriteonelineofcodetoperformcommontasks.ThefollowingschematicshowsthebasicelementsoftheSecurityApplicationBlock.
TheSecurityApplicationBlockexposestwointerfacesthatyoucanaccessinyourcode:
AnAuthorizationProviderinterface,whichexposesthesinglemethodnamedAuthorizethattakesaninstanceofanIPrincipalobjectcontainingdetailsoftheuser'sidentityandroles.Dependingonthewaythatyouconfiguretheblock,theauthorizationcantakeplaceeitherthroughWindows®AuthorizationManager(AzMan)againstActive
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®.
TypicalUsageoftheSecurityApplicationBlock
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheSecurityApplicationBlock?
TheSecurityApplicationBlockincludesimplementationsoffunctionalitythatmakesiteasytoperformauthorization,security-relatedcaching,andsessionmanagement.Ifyourapplicationsrequiretheprovidedimplementations,youcanusetheSecurityApplicationBlocktoprovidethisfunctionality.However,theblockisalsodesignedtobeextensibleandincludesgenericprovidersforeachfunction.Youcanadapttheproviderstomeetyourownsecurityrequirements.
ScenariosfortheSecurityApplicationBlock
BenefitsoftheSecurityApplicationBlock
LimitationsoftheSecurityApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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
therestrictionsonusingtheRsaProtectedConfigurationProvider.7. (Optional)Inthepropertiespane,settheRequirePermissionproperty
toTrueorFalse.ThedefaultisTrue.8. (Optional)Inthepropertiespane,settheDefaultAuthorization
Providerproperty.Thisistheauthorizationproviderinstancetouseifoneisnotspecifiedinthecode.Thedefaultisnone.
9. (Optional)Inthepropertiespane,settheDefaultSecurityCacheProviderproperty.Thisisthesecuritycacheproviderinstancetouseifoneisnotspecifiedinthecode.Thedefaultisnone.
AfteryouaddtheSecurityApplicationBlocktotheapplicationconfiguration,youneedtoconfiguresomeorallofthefollowingelements:
AuthorizationRuleProviderAzManProviderCustomAuthorizationProviderSecurityCacheCustomSecurityCacheProvider
AuthorizationRuleProvider
AzManProvider
CustomAuthorizationProvider
SecurityCache
CustomSecurityCacheProviderToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
securityConfigurationElement
authorizationProvidersChildElement
rulesChildElement
securityCacheProvidersChildelement
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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#
usingMicrosoft.Practices.EnterpriseLibrary.Security;
VisualBasic
ImportsMicrosoft.Practices.EnterpriseLibrary.Security
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
MicrosoftEnterpriseLibrary5.0
ObtainingaTemporaryTokenforanAuthenticatedUser
Anexampleofwhenyoumightwanttoobtainatemporarytokenforanauthenticateduseriswhenyouwanttoimprovetheperformanceofyourapplicationbypassingthetokeninsteadoffrequentlyauthenticatingthesameuserduringasinglesession.Youcanusetheapproachdescribedheretosaveauserprincipalorauseridentityinthesecuritycacheandobtainatokenthatrepresentstheuser'sauthenticatedidentity.
TypicalGoals
Solution
UsingSaveIdentity
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
AuthenticatingaUserUsingaToken
Anexampleofwhenyoumightwanttouseatemporarytokenforauthenticationiswhenyouwanttoimprovetheperformanceofyourapplicationbypassingthetokeninsteadoffrequentlyauthenticatingauserduringasinglesession.Youcanusetheapproachdescribedheretoretrieveasaveduserprincipalorauseridentityfromthesecuritycacheusingatokenyoupreviouslyobtainedthatrepresentstheuser'sauthenticatedidentity.
TypicalGoals
Solution
UsingGetIdentity
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TerminatingaUserSession(ExpiringaToken)
Anexampleofwhenyoumaywanttoexpireatokeniswhenyouwanttomakesurethatthetokencannotbeusedbyanattackeraftertheuserlogsout.Youcanusetheapproachdescribedheretoexpireauserprincipalorauseridentity.
TypicalGoals
Solution
UsingExpireIdentity
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DeterminingWhetheraUserIsAuthorizedtoPerformaTask
Acommonsecurityrequirementistheneedtoauthorizeuserstoperformtasks.TheSecurityApplicationBlockhelpsbystandardizingaccesstoauthorizationproviderssuchastheAzManAuthorizationProviderortheAuthorizationRuleProvider,ortoauthorizationrulesstoredwithintheapplicationconfiguration.
TypicalGoals
Solution
UsingAuthorize
UsageNotesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignoftheSecurityApplicationBlock
TheSecurityApplicationBlockaddressesthefollowingareas:AuthorizationSecurity-relatedcaching
DesignHighlightsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesigningforSimplifiedAuthorization
Uniformimplementationsmakecodeeasiertounderstand,morepredictable,andeasiertomaintain.However,developerscanimplementauthorizationinapplicationsinmanydifferentways.Forexample,theymayhavetouseanapproachthatconformstothesecuritypoliciesoftheirorganizations.Alternatively,theymayuseapproachesthatsuittheneedsofparticulardepartmentsoroftheapplicationsthemselves.
TheSecurityApplicationBlockencapsulatesthelogicthatperformsauthorizationoperationsintoasingleinterfacethatspecifiesonlyasmallnumberofmethods.Thesemethodscanbeusedbydifferentauthorizationproviders.ThismeansthatapplicationsthatusetheSecurityApplicationBlockareconsistentinthewaysthattheyauthorizeuserstoperformtasks.ByusingtheSecurityApplicationBlock,thisconsistencyremainsacrosssingleprojects,multipleprojects,orenterprise-scalesolutions.
DesignImplications
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
MicrosoftEnterpriseLibrary5.0
ExtendingtheSecurityApplicationBlock
YouextendtheSecurityApplicationBlockthroughdesignatedextensionpoints.Typically,thesearecustomclasses,writtenbyyou,thatimplementaparticularinterfaceorderivefromanabstractclass.Becausethesecustomclassesexistinyourapplicationspace,youdonothavetomodifyorrebuildtheblock.Instead,youdesignateyourextensionsusingconfigurationsettings.
YoucanextendtheblockbyaddinganewtypeofAuthorizationProviderorbyaddinganewsecuritycacheproviderthatintegrateswithyourchosencachingmechanism.Thefollowingtableliststheinterfacesandbaseclassesthatyoucanusetoextendtheblock.
CustomProviderorExtension InterfaceorBaseClass
AuthorizationProvider AuthorizationProvider
SecurityCacheProvider ISecurityCacheProvider
FordetailedinformationabouthowtointegratecustomproviderswiththeEnterpriseLibraryconfigurationsystemandconfigurationtoolsseeCreatingCustomProvidersforEnterpriseLibrary.
CreatinganAuthorizationProviderToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
MicrosoftEnterpriseLibrary5.0
SecurityApplicationBlockEventLogEntries
ThistopicliststheSecurityApplicationBlockeventlogentries.Thelisteneristheclassthatraisedtheevent.
ConfigurationFailureEventToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
DesignoftheValidationApplicationBlock.ThistopicincludesaclassdiagramoftheValidationApplicationBlock.ExtendingandModifyingtheValidationApplicationBlock.Thistopicexplainshowtoextendtheapplicationblockbyaddingcustomvalidatorsandattributes.Italsocontainsadviceabouthowtomodifythesourcecode.DeploymentandOperations.Thistopicexplainshowtodeployandupdatetheapplicationblockassemblies.Italsoexplainstheapplicationblock'sinstrumentation.
MoreInformationForrelatedinformation,seethefollowingpatterns&practicesguides:
HowTo:ProtectFromInjectionAttacksinASP.NETSecurityPractices:ASP.NETSecurityPracticesataGlanceMicrosoftApplicationArchitectureGuide,2ndEdition
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
ExampleApplicationCodeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhenShouldIUsetheValidationApplicationBlock?
YoushouldconsiderusingtheValidationApplicationBlockifyouwanttoencapsulatevalidationgoodpracticeintoeasilymaintainablecodethatyoucanreuse.Encapsulationalsoallowsyoutoseparatetheapplicationcodefromthevalidationlogic.Insomesituations,youmaybeabletoupdatethevalidationlogicwithoutredeployingtheapplication.
Inaddition,considerusingtheblockwhenyourvalidationcodemustworkacrossmultiplelayersoftheapplication'sarchitecture.Bydefiningrulesintheconfigurationforeachsegment,youcanreusethesamerulesetsinmultiplelocationswithinyourcode.
ScenariosfortheValidationApplicationBlock
BenefitsoftheValidationApplicationBlock
AlternativestotheValidationApplicationBlockToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DevelopingApplicationsUsingtheValidationApplicationBlock
ThissectiondescribeshowtousetheValidationApplicationBlockinyourapplications.Itexplainshowtoconfiguretheapplicationblock,andhowtoincorporatetheapplicationblockintoyourapplication.Thissectionincludesthefollowingtopics:
EnteringConfigurationInformationAddingApplicationCodeUsingtheValidationBlockValidatorsUnderstandingCommonValidatorPropertiesUnderstandingValidationResultsHowValidatorsAreCreatedValidationandInheritance
Allapplicationblocksshipasbinaryassembliesandassourcecode.Ifyouwanttousethesourcecode,youmustcompileit.TolearnhowtocompiletheEnterpriseLibrarysourcecode,seeBuildingEnterpriseLibraryfromtheSourceCode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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
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
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.
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.
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
validationElement
typeElement
rulesetElement
fieldsElement
methodsElement
propertiesElement
validatorElementToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
ImportsMicrosoft.Practices.EnterpriseLibrary.Validation.Validators
Note:ForVisualBasicprojects,youcanusetheReferencespageoftheProjectDesignertomanagereferencesandimportednamespaces.ToaccesstheReferencespage,selectaprojectnodeinSolutionExplorer.OntheProjectmenu,clickProperties.WhentheProjectDesignerappears,clicktheReferencestab.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
RegularExpressionValidatorRelativeDateTimeValidatorStringLengthValidatorTypeConversionValidatorSingleMemberValidators
Eachentrycontainsexamplesforhowtousethevalidatorwithattributesandwithcode.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
AndCompositeValidator
ClassName:AndCompositeValidator
AttributeName:ValidatorCompositionAttribute
Configurationtoolname:AndCompositeValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ContainsCharactersValidator
ClassName:ContainsCharactersValidator
AttributeName:ContainsCharactersValidatorAttribute
Configurationtoolname:ContainsCharactersValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DateTimeRangeValidator
ClassName:DateTimeRangeValidator
AttributeName:DateTimeRangeValidatorAttribute
Configurationtoolname:DateTimeRangeValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DomainValidator
ClassName:DomainValidator<T>
AttributeName:DomainValidatorAttribute
Configurationtoolname:DomainValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
EnumConversionValidator
ClassName:EnumConversionValidator
AttributeName:EnumConversionValidatorAttribute
Configurationtoolname:EnumConversionValidator
Description
Properties
Examples
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
NotNullValidator
ClassName:NotNullValidator
AttributeName:NotNullValidatorAttribute
Configurationtoolname:NotNullValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ObjectCollectionValidator
ClassName:ObjectCollectionValidator
AttributeName:ObjectCollectionValidatorAttribute
Configurationtoolname:ObjectCollectionValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ObjectValidator
ClassName:ObjectValidator
AttributeName:ObjectValidatorAttribute
Configurationtoolname:ObjectValidator
Description
Properties
Example
DifferencesbetweentheObjectValidatorandtheFactory-CreatedValidatorsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
OrCompositeValidator
ClassName:OrCompositeValidator
AttributeName:ValidatorCompositionAttribute
Configurationtoolname:OrCompositeValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
PropertyComparisonValidator
ClassName:PropertyComparisonValidator
AttributeName:PropertyComparisonAttribute
Configurationtoolname:PropertyComparisonValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RangeValidator
ClassName:RangeValidator<T>
AttributeName:RangeValidatorAttribute
Configurationtoolname:RangeValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RegularExpressionValidator
ClassName:RegexValidator
AttributeName:RegexValidatorAttribute
Configurationtoolname:RegularExpressionValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RelativeDateTimeValidator
ClassName:RelativeDateTimeValidator
AttributeName:RelativeDateTimeValidatorAttribute
Configurationtoolname:RelativeDateTimeValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
StringLengthValidator
ClassName:StringLengthValidator
AttributeName:StringLengthValidatorAttribute
Configurationtoolname:StringLengthValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TypeConversionValidator
ClassName:TypeConversionValidator
AttributeName:TypeConversionValidatorAttribute
Configurationtoolname:TypeConversionValidator
Description
Properties
ExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
techniquecanbeusedwiththeFieldValueValidatorandMethodReturnValueValidator.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UnderstandingCommonValidatorProperties
ThereareanumberofpropertiesdefinedfortheValidatorclass.ThesepropertiesarealsoexposedbytheValidatorAttributeclass,whichmeansthattheycanbeusedwithanyattributethatderivesfromthisclass.
Thesepropertiesarethefollowing:MessageTemplate.Formoredetails,seeUsingtheMessageTemplateProperty.MessageTemplateResourceNameandMessageTemplateResourceType.Formoredetails,seeUsingtheMessageTemplateResources.Negate.Formoredetails,seeUsingtheNegateProperty.Tag.Formoredetails,seeUsingtheTagProperty.Ruleset.Formoredetails,seeUsingtheRulesetProperty.
UsingtheMessageTemplateProperty
UsingtheMessageTemplateResources
UnderstandingMessageTemplateTokens
UsingtheNegateProperty
UsingtheTagProperty
UsingtheRulesetPropertyToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
failedvalidation.
Message Thisisamessagethatdescribesthevalidationfailure.
Tag ThisisavaluesuppliedbytheuserastheTagpropertyofthevalidator.Typically,itisusedforcategorizationorfiltering.Thetagcanbesuppliedthroughtheconstructorbutitistypicallyseteitherbyusingapropertyinthevalidationattributesorwithconfiguration.
Target Thisistheobjecttowhichthevalidationrulewasapplied.
Validator Thisisthevalidatorthatperformedthevalidation.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
CreatingValidatorswithConfiguration
CreatingValidatorswithAttributesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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{...}
}
}
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
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
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].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
KeyScenarios
ThissectiondescribesthemostcommonsituationsdevelopersmustaddresswhenusingtheValidationApplicationBlock.Thefollowingscenariosareincluded:
ValidatingObjectsCreatingValidatorsProgrammaticallyUsingValidationBlockAttributesUsingDataAnnotationAttributesDefiningAttributesinMetadataClassesUsingSelfValidationIntegratingwithASP.NET,WPF,WindowsForms,andWCF
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ValidatingObjects
Youcanvalidateanobjectonceyouhaveobtainedareferencetoavalidationfactoryandattachedthevalidatorsandtherulesets.TheeasiestwaytoobtainareferencetoavalidationfactoryisthroughtheEnterpriseLibrarycontainer,asdescribedinCreatingandReferencingEnterpriseLibraryObjects.Thistopicdemonstratesthefollowingtechniques:
CreatingValidatorInstancesSpecifyingtheLocationofValidationRulesValidatinganObjectValidatingObjectsUsingRuleSets
Note:InpreviousreleasesofEnterpriseLibrary,youcouldusethestaticValidationfacadetovalidateobjectswithoutfirstcreatingavalidator.YoucouldalsousethestaticValidationFactoryclass(asopposedtothereplacementnon-staticValidatorFactoryclass)tocreatevalidatorinstances.Theseapproachesaresupportedinthisreleaseforbackwardscompatibilitywithexistingapplicationcode.However,totakeadvantageofbenefitsavailablewhenusingdependencyinjection,youshouldusethetechniquesdescribedinthissection.Forinformationaboutusingthestaticfacades,seetheEnterpriseLibrarydocumentationonMSDN.
CreatingValidatorInstances
SpecifyingtheLocationofValidationRules
ValidatinganObject
ValidatingObjectsUsingRuleSetsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
class.ThevariableshortStringValidatorcontainsthereferencetothisinstance.YoucanusetheAndCompositeValidatorclasstocreateacompositevalidator.Inthisexample,thecompositevalidatorcontainsaNotNullValidatorinstanceandaStringLengthValidatorinstance.
AfteryouprogrammaticallycreateaValidatorobject,youcanusetheValidatemethodtovalidateanobjectasdescribedinthetopicValidatingObjects.NoticehowthesecondcalltotheValidatemethodusestheoverloadthatacceptsanexistinginstanceoftheValidationResultsclassandaddsanyvalidationerrorsitfindstothelist.
Asanalternativetocreatingvalidatorsbyexecutingtheconstructor,youcanresolveindividualvalidatorsthroughtheEnterpriseLibraryContainer.Ifyouspecifyanamewhenyouresolvetheinstance,thisisinterpretedasthenameoftherulesetforthatvalidatortousewhenvalidatingobjects.YoumustaddtheValidationBlockExtensiontothecontainertousethisapproach.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingValidationBlockAttributes
Validationattributes(boththebuilt-inValidationApplicationBlockattributesandthosedescribedinthetopicUsingDataAnnotationAttributes)canbeusedwithvarioustargetsthatincludeclasses,fields,properties,methods,and(inlimitedcases)parameters.Forinformation,seeValidationAttributeTargets.Thereisalsoasetofattributesthatallowyoutochangethebehaviorofotherattributes.ThesearediscussedinValidationModifierAttributes.Youcanalsospecifytheattributesyouwanttouseinaseparatemetadataclass.Formoredetailsofthis,seeDefiningAttributesinMetadataClasses.
UsingValidationBlockAttributestoDefineValidationRuleSets
ValidationAttributeTargets
ValidationModifierAttributesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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.
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
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.
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
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")>_
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;}
}
[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)
results.AddResult(result2)
EndSub
EndClass
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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
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.
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
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.
ConfiguringValidationthroughAttachedPropertiesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
IncludingtheValidationApplicationBlock
DefiningaBehavior
DefininganEndpoint
ReportingValidationFaults
ValidatingParametersToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignoftheValidationApplicationBlock
TheValidationApplicationBlockisdesignedtodothefollowing:Encapsulatethelogicusedtoperformthemostcommonvalidationtasksintominimalapplicationcode.Relievedevelopersoftherequirementtowriteduplicatecodeandcustomcodeforcommonvalidationtasks.Allowvalidationrulestobechangedaftertheapplicationhasbeendeployed,andensurethatchangeshappensimultaneouslyandconsistently.
DesignHighlightsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
MicrosoftEnterpriseLibrary5.0
DeploymentandOperations
Twoofanadministrator'smaintaskswillbetoseethattheinitialdeploymentoftheValidationApplicationBlockisplannedandmanagedandthatsubsequentupdatesaredeployedwithminimalimpacttoexistingapplicationsthatusetheapplicationblock.FordetailsofdeployingandupdatingEnterpriseLibraryandtheapplicationblocks,seeDeployingEnterpriseLibrary.
Inaddition,administratorsmustdecidewhethertheywanttousetheinstrumentationexposedbytheapplicationblock.Fordetailsofhowtoenableanddisableinstrumentation,seeEnablingInstrumentation.ForinformationabouttheinstrumentationcontainedwithintheValidationApplicationBlock,seethefollowingtopics:
ValidationApplicationBlockPerformanceCountersValidationApplicationBlockEventLogEntries
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
MicrosoftEnterpriseLibrary5.0
ValidationApplicationBlockEventLogEntries
TheValidationApplicationBlockisinstrumentedtologentriestotheapplicationeventlogifavalidationfails.ThefailureisattributedtoEnterpriseLibraryValidationanditisdescribedasanError.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UnityDependencyInjectionandInterception
WelcometoUnity.ThefollowingsectionsofthisguidancedescribethewaysthatyoucanuseUnitydependencyinjectionandUnityinterceptioninyourapplications.Thesectionsare:
WhatIsUnity?WhatDoesUnityDo?WhenShouldIUseUnity?AboutThisReleaseofUnityConfiguringUnity
UsingUnityinApplicationsDesignofUnityExtendingandModifyingUnityDeploymentandOperationsUnityQuickStarts.ThistopicwalksthroughtheQuickStartapplicationsthatdemonstratehowtoexecutecommonoperationsinyourapplications.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
informationrequiredbyyourapplication.UsingUnityinApplications.ThistopicexplainshowtouseUnityinyourownapplications.ItexplainshowtoaddUnitytoyourapplication,howtoresolveobjects,andhowtotakeadvantageofthemanyothercapabilitiesofUnity.DesignofUnity.ThistopicexplainsthedecisionsthatwentintodesigningUnityandtherationalebehindthosedecisions.ExtendingandModifyingUnity.ThistopicexplainshowtoextendUnityandhowtomodifythesourcecode.DeploymentandOperations.ThistopicexplainshowtodeployandupdatetheUnityassembliesandusetheinstrumentationexposedbyUnity.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
WhatDoesUnityDo?
Byusingdependencyinjectionframeworksandinversionofcontrolmechanisms,youcangenerateandassembleinstancesofcustomclassesandobjectsthatcancontaindependentobjectinstancesandsettings.ThefollowingsectionsexplainthewaysthatyoucanuseUnity,andthefeaturesitprovides:
TheTypesofObjectsUnityCanCreateRegisteringExistingTypesandObjectInstancesManagingtheLifetimeofObjectsSpecifyingValuesforInjectionPopulatingandInjectingArrays,IncludingGenericArraysInterceptingCallstoObjects
TheTypesofObjectsUnityCanCreate
RegisteringExistingTypesandObjectInstances
ManagingtheLifetimeofObjects
ConfiguringTypesforInjectionintoConstructors,Methods,andProperties
PopulatingandInjectingArrays,IncludingGenericArrays
InterceptingCallstoObjects
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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®.
ScenariosforUnity
BenefitsofUnity
LimitationsofUnityToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
AboutThisReleaseofUnity
ThissectioncontainsthefollowingtopicsthatwillhelpyoutounderstandthisreleaseofUnityandhelpyouunderstandhowtouseitalongsideearlierversionsormigrateyourapplicationstothisversion.Thissectionincludesthefollowingtopics:
ChangesinThisReleaseTargetAudienceandSystemRequirementsMigrationandSide-by-SideExecutionRelatedpatterns&practicesLinksCopyrightandTermsofUse
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ChangesinThisRelease
Unity2.0–April2010isanewreleaseoftheMicrosoftpatterns&practicesUnitydependencyinjectionandinterceptionsystem.Thisreleasealsoincludesadditionsinfunctionality,andhasbeenadaptedtoworkwithMicrosoftVisualStudio®2010;andwiththeMicrosoft.NETFrameworkversions3.5SP1and4.0.
GotoCodePlexforinformationonKnownIssues.
ThefollowingsectionsdiscussthechangestoUnity:
BreakingChangestoUnity
ChangesinUnity
BreakingChangestoUnity
ChangesinUnityToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TargetAudienceandSystemRequirements
Thisguidanceisintendedforsoftwarearchitectsandsoftwaredevelopers.Togetthegreatestbenefitfromthisguidance,youshouldhaveanunderstandingofthefollowingtechnologies:
MicrosoftVisualC#®orMicrosoftVisualBasic.NETMicrosoft.NETFramework
SystemRequirementsandPrerequisites
SystemRequirementsforUnityforSilverlightToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
PartialMigrationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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®.
MigratingCustomExtensionsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
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
protectedusingAccessControlLists.Itisrecommendedthattheconfigurationstoreisinthesametrustboundaryandthatdecryptingtheconfigurationisdoneinthesametrustboundaryaftertheconfigurationisread.
Thecompletesetoftopicsinthissectionisasfollows:Design-TimeConfiguration
UsingtheConfigurationToolUsingDesign-TimeConfigurationSpecifyingTypesintheConfigurationFileSpecifyingValuesforInjectionExtendingtheUnityConfigurationSchemaConfigurationFilesforInterceptionDefaultAliasesandAssemblies
Run-TimeConfigurationUsingRunTimeConfigurationRegisteringTypesandTypeMappingsCreatingInstanceRegistrationsRegisteringInjectedParameterandPropertyValuesRegisteringGenericParametersandTypesRegisteringContainerExtensionsRegisteringInterception
Forinformationaboutusingcontainerhierarchies,seeUsingContainerHierarchies.ForinformationaboutusingUnity,seeUsingUnityinApplications.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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.
MicrosoftEnterpriseLibrary5.0
UsingtheConfigurationTool
NotavailableforUnityconfiguration.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
orderthatisnotrequiredbytheconfigurationruntimebutmakestheschemamorerobust.Theorderofchildrenisasfollows:oneoptionallifetime,oneoptionalconstructor,andthenasmanyofmethod,property,interceptor,interceptionBehavior,addInterfaceandanycustomelementasdesired,inanyorder.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingDesign-TimeConfiguration
UsingUnitytypicallyrequirestheconfigurationofaDependencyInjection(DI)container.YoucanconfigureacontainerbyusingtheUnityAPI,a.NETconfigurationfile,ortoalimiteddegreebyusingattributes.ThistopicdescribeshowtouseanXMLconfigurationfiletosupplytherequiredconfigurationinformation..
Dependencyinjectionisaveryflexiblepattern,andtobeusedsuccessfullyrequiresthedevelopertoprovideinformationtothecontainerabouthisapplications.Thetwomostcommonconfigurationtasksaresettinguptypemappingsandconfiguringinjectionofatype.Typemappingsenableyoutorequestatypefromthecontainerthatresultsinthecontainerreturninganinstanceofadifferenttype(typicallyaderivedclassorinterfaceimplementation).Configuringinjectionforatypeentailsspecifyinginformationsuchaswhichconstructorgetscalled,whichpropertiesgetinjected,andwhattheirvaluesare.TheUnityconfigurationschemaencompassesthesetypesofconfigurationandisalsoextensibletoallowforadditionalkindsofconfigurationsuchasUnityinterceptionconfiguration,seeTheUnityConfigurationSchema.Thefollowingsectionsprovidemoredetails:
FormatoftheUnityConfigurationFileLoadingConfigurationFileInformationintoaContainerLoadingtheConfigurationfromAlternativeFiles
FormatoftheUnityConfigurationFile
LoadingConfigurationFileInformationintoaContainer
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
SpecifyingTypesintheConfigurationFile
ThistopicexplainshowtousetypesinUnityconfigurationfiles.AtthecoreofUnity'sfunctionalityaretypesandhowyouspecifyandhandlethem.Youwillneedtospecifytypesmanytimesinthetypicalconfigurationfile.Theconfigurationfileshavetheirownsetofrulesforwritingtypenames—rulesthatdifferfromthosefortypeswritteninC#orVisualBasic.TheserulesapplyeverywhereyoucanspecifyatypeintheUnityconfigurationsection.
Thistopiccontainsthefollowingsectionthatdescribehowyoucanspecifytypes:
CLRTypeNamesTypeAliasesAutomaticTypeLookupDefaultAliasesandAssembliesGenericTypes
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.
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.
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
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
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
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
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[,]
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
The<register>Element
The<lifetime>Element
The<constructor>Element
The<property>Element
The<method>Element
The<param>Element
The<dependency>Element
The<value>Element
The<optional>Element
The<array>Element
The<extension>Element
The<instance>Element
The<namespace>Element
The<assembly>Element
The<alias>Element
The<sectionExtension>ElementToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
SpecifyingValuesforInjection
ThistopicexplainshowtoconfiguretheinformationrequiredsothatUnitywillautomaticallypopulateconstructorandmethodparametersandpropertyvalueswhenitresolvesinstancesoftypes.The<param>and<property>elementsbothletyouspecifyavaluetobesuppliedfortheparameterorproperty,respectively.Therearemanydifferentkindsofvaluesthatcanbespecified,eachwithaseparateelement.Inaddition,theUnityconfigurationschemasupportsashorthandnotationforthemostcommoncases.
FormoreinformationabouttheformatoftheUnityconfigurationfile,seeUsingDesign-TimeConfiguration.
Thistopiccontainsthefollowingsectionsdescribingvaluesforinjection:
ResolvingValuesfromtheContainer
GivingValuesinConfiguration
ConfiguringArrayValues
ResolvingValuesfromtheContainer
GivingValuesinConfiguration
ConfiguringArrayValuesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
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.
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
UsingtheConfigurationFiletoEnableInterception
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
The<interceptor>Element
The<interceptionBehavior>Element
The<addInterface>Element
The<interception>Element
The<policy>Element
The<matchingRule>Element
The<callHandler>Element
The<interceptors>Element
Theinterceptors<interceptor>Element
The<default>Element
The<key>ElementToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
ResolvingObjects.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingRunTimeConfiguration
Thistopicdiscussessomeofthefactorsyoushouldkeepinmindwhenusingrun-timeconfiguration,andexplainssomefeaturesoftheUnityrun-timeconfigurationmechanism.Fordetailsonhowtospecifyconfigurationusingaconfigurationfile,seeDesign-TimeConfiguration.
UsingtheUnityContainerFluentInterfaceToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RegisteringTypesandTypeMappings
Thistopicexplainshowtoregistertypesinthecontainer.Registeringatypeletsyouconfigurehowthecontainercreatesinstancesofthespecifiedtype.Ingeneral,youwillcreatemappingsbetweenaninterfaceandatypethatimplementstheinterface,orbetweenabaseclassandatypethatinheritsthatbaseclass.However,youcanregistertypesinthecontainerwithoutcreatingamapping.
TheRegisterTypemethodregistersatypewiththecontainer.Attheappropriatetime,thecontainerwillbuildaninstanceofthetypeyouspecify.ThiscouldbeinresponsetodependencyinjectionthroughclassattributesorwhenyoucalltheResolvemethod.Thelifetimeoftheobjectitbuildswillcorrespondtothelifetimeyouspecifyintheparametersofthemethod.Ifyoudonotspecifyavalueforthelifetime,thetypeisregisteredforatransientlifetime,whichmeansthatanewinstancewillbecreatedoneachcalltoResolve.
ThistopiccontainsthefollowingsectionsthatexplainuseoftheRegisterTypemethod:
RegisteringanInterfaceorClassMappingtoaConcreteTypeRegisteringaNamedTypeRegisteringTypeMappingswiththeContainerUsingaLifetimeManagerwiththeRegisterTypeMethodSummaryoftheRegisterTypeMethodOverloadsMoreInformation
RegisteringanInterfaceorClassMappingtoaConcreteType
RegisteringaNamedType
RegisteringTypeMappingswiththeContainer
UsingaLifetimeManagerwiththeRegisterTypeMethod
SummaryoftheRegisterTypeMethodOverloads
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CreatingInstanceRegistrations
Thistopicexplainshowtoregisterexistingobjectsinthecontainerthatyoucanresolveinyourapplication.ThistechniqueisusefulifyoualreadyhaveaninstanceofanobjectthatyouhavepreviouslycreatedandwantUnitytomanageitslifetime,orifyouwantUnitytoinjectthatobjectintootherobjectsthatitisresolving.
TheRegisterInstancemethodregistersanexistinginstancewiththecontainer.Youspecifytheinstancetypeandoptionallifetimeintheparameterlist.Thecontainerwillreturnthespecifiedexistinginstanceforthedurationofthespecifiedlifetime.TheRegisterInstancemethodoverloadsareverysimilartotheRegisterTypemethodoverloads,buttheyacceptanadditionalparameter,theobjectinstancetoregister.Theuseoftheregistrationtypeandanoptionalnameareidenticalforthetwomethods.
Whenresolvingtypeswithdependencies,instancesofobjectsaddedtothecontainerwiththeRegisterInstancemethodactjustlikethoseregisteredthroughRegisterType.TheRegisterTypemethodwithaContainerControlledLifetimeManagerautomaticallygeneratesthissingleinstancethefirsttimeyourcodecallsit,whiletheRegisterInstancemethodacceptsanexistinginstanceforwhichitwillreturnreferences.Ifyoudonotspecifyalifetimemanager,thecontainerwilluseaContainerControlledLifetimeManageranditwillreturnareferencetotheoriginalobjectoneachcalltoResolve.
Thistopiccontainsthefollowingsections,whichexplaintheuseoftheRegisterInstancemethod:
RegisteringanExistingObjectInstanceofanInterfaceorTypetoaContainerUsingaLifetimeManagerwiththeRegisterInstanceMethodSummaryoftheRegisterInstancesMethodOverloadsMoreInformationonUsingtheRegisterInstanceMethod
RegisteringanExistingObjectInstanceofanInterfaceorTypetoaContainer
UsingaLifetimeManagerwiththeRegisterInstanceMethod
SummaryoftheRegisterInstanceOverloads
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RegisteringInjectedParameterandPropertyValues
ThistopicexplainshowtoconfigureacontainertoperformdependencyinjectionatruntimebyusingtheRegisterTypemethodoverloadswiththeInjectionMembersparameterandavoidrelyingonannotatingtheclassestoresolvewithattributes.ThistopicincludesinformationonconfiguringUnitytoautomaticallypopulateconstructorandmethodparametersandpropertyvalueswhenitresolvesinstancesoftypes.
ThistopiccontainsthefollowingsectionstoexplaintheuseoftheInjectionMembersmethods:
RegisteringInjectionforParametersPropertiesandMethodsUsingInjectionMembersInjectingArraysatRunTimeSummaryoftheInjectionMemberMethodsandOverloadsForMoreInformationonInjectionMembers
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
RegisterConstructorsandParameters
SpecifyaPropertyforInjection
SpecifyaMethodforInjection
InjectingSpecificArrayInstances
InjectingAllArrayNamedInstances
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RegisteringGenericParametersandTypes
Thistopicexplainshowyoucanregistertheinformationrequiredforinjectionforgenerictypes,includinggenericarrays.YoucanspecifyagenerictypewhenyouregisteratypeintheUnitycontainerinalmostexactlythesamewayasyouregisternon-generictypes.Unityprovidestwoclassesspecificallyforregisteringgenerics,GenericParameterforspecifyingthataninstanceofagenerictypeparametershouldberesolved,andGenericResolvedArrayParameterforspecifyingthatanarraycontainingtheregisteredinstancesofagenerictypeparametershouldberesolved.
Seethe"SpecifyingTypesintheConfigurationFile"sectionintheSpecifyingTypesintheConfigurationFiletopicformoredetailsongenerics,includingadiscussionofunbounded,closed,andopengenerictypes.
Thistopiccontainsthefollowingsectionsthatexplainregisteringgenerics:RegisteringGenericInterfacesandClassesRegisteringTypeMappingsForGenericsRegisteringGenericArraysSupportforGenericDecoratorChainsMethodsforRegisteringGenericParametersandTypesMoreInformation
RegisteringGenericInterfacesandClasses
RegisteringTypeMappingsforGenerics
RegisteringGenericArrays
MethodsforRegisteringGenericParametersandTypes
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RegisteringContainerExtensions
ThistopicexplainshowtoregisterinformationthatinstructsUnitytoloadandusecontainerextensionsthataddadditionalfunctionalitytothecontainer,andhowyoucanregisterconfigurationinformationfortheseextensions.
Thistopiccontainsthefollowingsectionsthatexplaincontainerextensions:AddingandRemovingExtensionsAccessingConfigurationInformationforExtensionsMethodsforRegisteringandConfiguringContainerExtensionsMoreInformation
AddingandRemovingExtensions
AccessingConfigurationInformationforExtensions
MethodsforRegisteringandConfiguringContainerExtensions
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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
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()))
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
RegisteringPolicyInjectionComponents
Thistopicexplainshowtoregisterthevariouselements,includinginterceptors,behaviors,policies,callhandlers,andmatchingrulesthatUnityusestoconfigureacontainerforinterceptionandforapolicyinjectionbehavior.
Whenyouconfigurepolicyinjectionyoumustspecifywhichobjectswillbeinterceptedwiththepolicyinjectionbehaviorandwhichpoliciesinthecontaineraretobeused.Thenwhenbuildingtheobject,thepolicyinjectionbehaviorissetupusingthepoliciesalreadydefinedinthecontainer.
Thistopiccontainsthefollowingsections:PolicyInjectionRun-TimeConfigurationDefiningPoliciesbyUsingtheAPI
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)()_
.AddPolicy("policy")_
.AddCallHandler(NewActionCallHandler(Function()_
System.Math.Max(System.Threading.Interlocked.Increment_
(intercepted),intercepted-1)))
DefiningPoliciesbyUsingtheAPIToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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
methodofthecontaineronlywhenyouneedtoretrieveareferencetoaspecificobject.Thisapproachisknownasservicelocator.Itismoreintrusiveintoyourapplication,butcanbesimplerifyourarchitecturedoesnotlenditselftohavingacentralcontainer.
Inadditiontodependencyinjection,developersmaywishtoimplementpatternssuchasInterception,Decorator,ChainOfResponsibility,andInterceptingFilter,whereacallfromaclientorprocesspassesthroughagraphofobjects,witheachoneabletoaccessandactupondetailsofthecall,suchasthemethodorpropertyname,theparametertypesandvalues,thereturnedtypeandvalue,andotherinformation.Unityachievesthisthroughinterceptionofmethodcalls,providingopportunitiestoapplypoliciestoobjectsusingatechniqueoftenreferredtoaspolicyinjection.
Unityprovidesacomprehensivedependencyinjectionandinterceptionmechanism,andiseasytoincorporateintoyourapplications.However,itdoeschangethewaythatyoudesigntheseapplications.Thefollowingsectionsofthistopicdescribeareaswheredependencyinjectionisuseful:
PluggableArchitecturesManagingCrosscuttingConcernsServiceandComponentLocationPolicyInjectionthroughInterception
PluggableArchitectures
ManagingCrosscuttingConcerns
ServiceandComponentLocation
PolicyInjectionthroughInterceptionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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;
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.
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.
ThefollowingtopicsdescribehowyoucanresolveobjectsusingtheResolveorResolveAllmethods:
ResolvinganObjectbyType.ResolvinganObjectbyTypeandRegistrationName.ResolvingAllObjectsofaParticularType.ResolvingObjectsbyUsingOverridesRetrievingContainerRegistrationInformation
FormoreinformationabouthowyoucanconfigureUnitywithtyperegistrationsandmappings,seeConfiguringUnity.
Formoreinformationabouthowyoucanperformdependencyinjectiononexistingobjectinstances,seeUsingBuildUptoWireUpObjectsNotCreatedbytheContainer.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ResolvinganObjectbyType
UnityprovidesamethodnamedResolvethatyoucanusetoresolveanobjectbytype,andoptionallybyprovidingaregistrationname.Registrationsthatdonotspecifyanamearereferredtoasdefaultregistrations.ThistopicdescribeshowtousetheResolvemethodtoresolvetypesandmappingsregisteredasdefaultregistrations.Forinformationaboutresolvingnamedregistrations,seeResolvinganObjectbyTypeandRegistrationName.
TheResolveMethodOverloadsforDefaultRegistrations
UsingtheResolveMethodwithDefaultRegistrations
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ResolvinganObjectbyTypeandRegistrationName
UnityprovidesamethodnamedResolvethatyoucanusetoresolveanobjectbytype,andoptionallybyprovidingaregistrationname.Registrationsthatspecifyanamearereferredtoasnamedregistrations.ThistopicdescribeshowtousetheResolvemethodtoresolvetypesandmappingsregisteredasnamedregistrations.Forinformationaboutresolvingdefaultregistrations,seeResolvinganObjectbyType.
TheResolveMethodOverloadsforNamedRegistrations
UsingtheResolveMethodwithNamedRegistrations
ResolvingGenericTypesbyName
MoreInformation
ResolvingGenericTypes
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ResolvingAllObjectsofaParticularType
Whenyouwanttoobtainalistofalltheregisteredobjectsofaspecifictype,youcanusetheResolveAllmethod.Thetwooverloadsofthismethodaccepteitheraninterfaceoratypename,andtheyreturnaninstanceofIEnumerablethatcontainsreferencestoallregisteredobjectsofthattypethatarenotdefaultmappings.ThelistreturnedbytheResolveAllmethodcontainsonlynamedinstanceregistrations.TheResolveAllmethodisusefulifyouhaveregisteredmultipleobjectorinterfacetypesusingthesametypebutdifferentnames.YoucanalsousetheparamstoprovideconstructoroverridesfortheResolveAllcalls.
TheResolveAllMethodOverloads
UsingtheResolveAllMethod
ResolvingAllGenericTypesbyNameToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
explicitcontainerconfiguration,thenthedefaultbehavioristhattheconstructorwiththemostparameterswillbeused.
Aparameterandpropertyoverrideneveraffectswhatelementgetsselected.Theyonlycontrolthevalueofthespecifiedparameterorproperty.Youdonotchangewhichconstructoriscalledwithanoverride,andyoudonotchangewhichpropertiesgetsetwithanoverride.
Note:Ifthepropertyisnotsetasadependencythroughattribute,containerAPI,orconfigurationfile,thentheoverridedoesnothing.
Thistopiccontainsthefollowingsectionstoexplainoverridesinmoredetail:UsingParameterOverridesUsingPropertyOverridesUsingDependencyOverridesMoreInformation
UsingParameterOverrides
UsingPropertyOverrides
UsingDependencyOverrides
MoreinformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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();
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...
//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
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.
MicrosoftEnterpriseLibrary5.0
RetrievingContainerRegistrationInformation
Youcanretrievealistofregistrationsfromacontainer,andcheckifaspecificregistrationisinthecontainer.
Thistopiccontainsthefollowingsections:ViewingtheContainerRegistrationsandMappingsCheckingfortheExistenceofaSpecificRegistration
ViewingtheContainerRegistrationsandMappings
CheckingfortheExistenceofaSpecificRegistrationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingContainerHierarchies
Unitysupportsnestedcontainers,allowingyoutobuildcontainerhierarchies.Nestingcontainersenablesyoutocontrolthescopeandlifetimeofsingletonobjects,andregisterdifferentmappingsforspecifictypes.Thistopiccontainsthefollowingsectionsthatdescribehowyoucancreatecontainerhierarchiesandusetheminyourapplications:
ConstructingandDisposingUnityContainersControllingObjectScopeandLifetimeRegisteringDifferentMappingsforSpecificTypes
ConstructingandDisposingUnityContainers
ControllingObjectScopeandLifetime
RegisteringDifferentMappingsforSpecificTypesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
lifetimemanager,willresultinanewinstancebeingcreatedbythecontaineranditwillbemadethesingletonforthatcontext.Thecreationofaninstanceunderthesecircumstancescouldfailifthecontainercannotresolvetheinstance,forexampleifyouregisteredaninstanceforaninterfacewithnomappingstoamatchingclass.
ForinformationaboutusinglifetimemanagerswiththeRegisterTypeandRegisterInstancemethods,seeRegisteringTypesandTypeMappingsandCreatingInstanceRegistrationsintheRun-TimeConfigurationsectionofthisdocumentation.Forinformationaboutspecifyingthelifetimeofobjectsatdesigntime,seeSpecifyingTypesintheConfigurationFile,andThe<instance>ElementintheDesign-TimeConfigurationsectionofthisdocumentation.
UnityBuilt-InLifetimeManagers
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
TheBuildUpMethodOverloads
UsingtheBuildUpMethod
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
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
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
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#
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()_
.RegisterType(OfIMyInterface,FirstObject)()_
.RegisterType(OfMyBaseClass,SecondObject)()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
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
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.
CopyCode
CopyCode
MultipleConstructorInjectionUsinganAttributeWhenatargetclasscontainsmorethanoneconstructorwiththesamenumberofparameters,youmustapplytheInjectionConstructorattributetotheconstructorthattheUnitycontainerwillusetoindicatewhichconstructorthecontainershoulduse.Aswithautomaticconstructorinjection,youcanspecifytheconstructorparametersasaconcretetype,oryoucanspecifyaninterfaceorbaseclassforwhichtheUnitycontainercontainsaregisteredmapping.
Touseattributedconstructorinjectionwhenthereismorethanoneconstructor
1. ApplytheInjectionConstructorattributetotheconstructorinthetargetclassthatyouwantthecontainertouse.Inthesimplestcase,thetargetconstructortakesasaparametertheconcretetypeofthedependentclass.Forexample,thefollowingcodeshowsatargetclassnamedMyObjectcontainingtwoconstructors,oneofwhichhasadependencyonaclassnamedMyDependentClassandhastheInjectionConstructorattributeapplied.C#
publicclassMyObject
{
publicMyObject(SomeOtherClassmyObjA)
{
...
}
[InjectionConstructor]
publicMyObject(MyDependentClassmyObjB)
{
...
}
}
VisualBasic
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
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
CopyCode
attributedconstructorandinjectthemintothetargetclass.Forexample,thefollowingcodeshowshowyoucaninstantiatetheexampletargetclassnamedMyObjectcontainingaconstructorthathasconstructordependenciesC#
IUnityContaineruContainer=newUnityContainer();
MyObjectmyInstance=uContainer.Resolve<MyObject>();
VisualBasic
DimuContainerAsIUnityContainer=NewUnityContainer()
DimmyInstanceAsMyObject=uContainer.Resolve(OfMyObject)()
5. Inadditiontousingconcretetypesasparametersofthetargetobjectconstructor,youcanuseinterfacesorbaseclasstypes,andthenregistermappingsintheUnitycontainertotranslatethesetypesintothecorrectconcretetypes.Fordetails,seesteps5and6oftheprocedureSingleConstructorAutomaticInjection.
NotesonUsingConstructorInjection
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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#
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
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]
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
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
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")>_
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>();
//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
UsingOptionalDependencies
NotesonUsingProperty(Setter)Injection
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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#
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#
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
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)()
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
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.
NotesonUsingMethodCallInjection
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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)
...
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:
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.
MicrosoftEnterpriseLibrary5.0
InterceptionwithUnity
Unityinterceptionenablesyoutoeffectivelycapturecallstoobjectsandaddadditionalfunctionalitytothetargetobject.Interceptionisusefulwhenyouwanttomodifythebehaviorforindividualobjectsbutnottheentireclass,verymuchasyouwoulddowhenusingtheDecoratorpattern.Itprovidesaflexibleapproachforaddingnewbehaviorstoanobjectatruntime.
Thissectioncontainsthefollowingtopicsthatwillhelpyoutounderstandinterception:
AboutUnityInterception.ThissectionofthistopicdescribesthebasicprinciplesofinterceptioninUnity.ScenariosforInterception.ThistopicdescribescommonscenariosaddressedbyUnityinterception.BehaviorsforInterception.ThistopicdescribesbehaviorsyoumightimplementwiththeIInterceptionBehaviorinterfacetoconfigureacontainerthroughtheRegisterTypemethod.ConfiguringaContainerforInterception.ThistopicdescribeshowtoconfiguretheUnitycontainerforinterception.UnityInterceptionTechniques.ThistopicdescribesindetailthedesignofUnityinterception.UsingInterceptioninApplications.ThistopicdescribeshowyouuseUnityinterceptioninyourapplications.UsingInterceptionandPolicyInjection.ThistopicexplainshowpolicyinjectionthroughinterceptionworksinUnity,howyoucanusematchingrulestoselecttargetclassesandclassmembersforpolicyinjection,andhowyoucanusetheEnterpriseLibrarycallhandlerswithUnity.
AboutUnityInterceptionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ScenariosforInterception
Unityinterceptionaddressesthefollowingscenarios:Addingresponsibilitiestoindividualobjectsandnottheentireclassandavoidingastaticsolution,muchasinadecoratorpattern.Inamannersimilartothewayadecoratorforwardsrequeststotheobjectandenablesyoutoperformadditionalactionsbeforeorafterforwardingtherequest,interceptioninterceptsthecalltothetargetobjectanddynamicallyaddsbehaviorstoindividualobjectswithoutaffectinganyotherobjects.Thiscanbeusefulinmanagingcrosscuttingconcernsthataccesscommonfeaturessuchasloggingorvalidation.Toaugmentormodifythebehaviorfromexistingclassesthatyoucannotmodify,providedthattheyareinterceptablebytheavailableinterceptionmechanisms.Enablingthedeveloperandadministratortoconfigurethebehaviorofobjectsinanapplicationthroughconfigurationwhenusedinconjunctionwithadependencyinjection(DI)container,byaddingorremovingbehaviorsthatexecutecommontasksoraddcustomfeatures.Enablingthedeveloperandadministratortocapturecallstoobjectsandaddorremovebehaviorsthatexecutecommontasksoraddcustomfeaturesatruntime,butinthiscaseindependentofaDIcontainer.Minimizingtheworkrequiredandthecodethatthedevelopermustwritetoperformcommontaskswithinanapplication,suchaslogging,validation,authorization,andinstrumentation.Reducingdevelopmenttimeandcost,andminimizingbugsincomplexapplicationsthatusecommonandsharedtasksandservices.
BenefitsofUsingUnityInterception
LimitationsofUnityInterception
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
.NETFramework.YoucanimplementIDataErrorInfoinaclassandbindtheclassconcreteobjecttotheDataGridViewcontrolthroughtheBindingsourceproperty.ThenusetheValidationApplicationBlocktovalidatetheclassobjectandstoretheresultsforeachproperty.
Implementingamockingframeworkthroughaninterceptionbehaviorcouldbeusefulincaseswherethecoderequiresaninterfacethathasnoimplementation.Thebehaviorcangiveyouamockupinterface.Youcoulduseamockingframeworktoimplementamockdatabase,mocklogger,ormockbuildercontext.
Thefollowingtopicsexplainordemonstrateinterceptionbehaviorsinmoredetail:
CustomInterceptionBehaviorsImplementIDataErrorInfoExample
CustomInterceptionBehaviors
ImplementINotifyPropertyChangedExampleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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:
AddingtheInterceptionExtensiontotheContainerConfiguringInterceptionofaTypeMoreInformation
AddingtheInterceptionExtensiontotheContainer
ConfiguringInterceptionofaType
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UnityInterceptionTechniques
Inordertoperforminterception,Unitymustbeabletocapturetheoriginalcallandpassitthroughabehaviorspipelinetothetargetobject,thenpasstheresultbackthroughthebehaviorspipelinetotheoriginalcaller.Thetwocommonapproachestotheinterceptionprocessareinstanceinterceptionandtypeinterception,andUnityprovidestechniquesforboth.Instanceinterceptorsworkbycreatingaproxytotheinterceptedinstance.Typeinterceptorsworkbyderivinganewtypethatimplementsinterception.Theinstanceinterceptiontargetistheoriginal,non-interceptedobject,butwhenperformingtypeinterceptionthetargetisinterceptedandaderivedobjectused.
Note:Instanceinterceptionworksonlyoninstancemethods;itdoesnotworkforstaticmethodsorconstructorssincetheconstructorhasalreadyexecutedbythetimetheclientcodegetsbackaninterception-readyobject.Instanceinterceptioncanonlyinterceptpublicinstancemethods.Typeinterceptioncaninterceptpublicandprotectedmethods.
Thistopiccontainsthefollowingsectionsthatwillhelpyoutounderstandinterception:
InstanceInterceptionTypeInterceptionComparisonofInterceptionTechniquesSummaryofInterceptionApproaches
InstanceInterceptionInstanceinterceptionworkswithbothexistinginstancesofobjects,andwithnewinstancescreatedbyUnity.Thefollowingschematicshowsthebasicprocessofinstanceinterception.
WhentheapplicationresolvestheobjectthroughtheUnitycontainer,theUnityinterceptioncontainerextensionmanagestheprocess.Itobtainsaneworexistinginstanceoftheobjectfromthecontainer,andcreatesaproxytotheobject.Thenitcreatesthehandlerpipelineandconnectsittothetargetobjectbeforereturningareferencetotheproxy.Theclientthencallsmethodsandsetspropertiesontheproxyasthoughitwerethetargetobject.
Note:UnityinterceptioncanbeusedwithoutaUnityDIcontainerbyusingthestand-aloneAPIthroughthestaticInterceptclass.Formoreinformation,seeUsingInterceptioninApplications.
Thesecallspassthroughtheinterceptionbehaviors,executingthepreprocessingstageofeachone,withthefinalbehaviorinthechainpassingthecalltothetargetobject.Thereturnvaluefromthetargetobjectpassesbackthroughthebehaviorsinthereverseorder,executingthepost-processingstageofeachone.Thefirstbehaviorinthepipelinethenpassestheresultbacktothecaller.
Instanceinterceptionisthemostcommonandwidelyusedtechnique.ItcanbeusedwithobjectsthateitherimplementtheMarshalByRefObjectabstractclass,orimplementapublicinterfacethatdefinesallofthemethodstobeintercepted.Unityprovidesthetwointerceptors,TransparentProxyInterceptorandInterfaceInterceptor,thatsupportthesetwoscenarios.Formoredetails,seethetablesinComparisonofInterceptionTechniqueslaterinthistopic.
TypeInterceptionTypeinterceptionusesaderivedclassinsteadofaproxy.Asdescribedintheprevioussection,instanceinterceptionworksbycreatingaproxytothetargetobject.Typeinterception,ontheotherhand,morecloselyresemblesaspect-orientedprogramming(AOP)techniquescommoninJava-basedsystems.Typeinterceptionavoidsthepossibleperformancepenaltiesofusingaproxyobjectbydynamicallyderivinganewclassfromtheoriginalclass,andinsertingcallstothebehaviorsthatmakeupthepipeline.Thefollowingschematicshowsthebasicprocessoftypeinterception.
WhentheapplicationresolvestherequiredtypethroughtheUnitycontainer,theUnityinterceptioncontainerextensioncreatesthenewderivedtypeandpassesit,ratherthantheresolvedtype,backtothecaller.Becausethetypepassedtothecallerderivesfromtheoriginalclass,itcanbeusedinthesamewayastheoriginalclass.Thecallersimplycallstheobject,andthederivedclasswillpassthecallthroughthebehaviorsinthepipelinejustasisdonewhenusinginstanceinterception.
Note:
UnityinterceptioncanbeusedwithoutaUnityDIcontainerbyusingthestand-aloneAPIthroughthestaticInterceptclass.Formoreinformation,seeUsingInterceptioninApplications.
However,duetothenatureofthedynamictypegeneration,therearesomelimitationswiththisapproach.Itcanonlybeusedtointerceptpublicandprotectedvirtualmethods,andcannotbeusedwithexistingobjectinstances.Ingeneral,typeinterceptionismostsuitedtoscenarioswhereyoucreateobjectsespeciallytosupportinterceptionandallowfortheflexibilityanddecouplingprovidedbypolicyinjection,orwhenyouhavemappingsinyourcontainerforbaseclassesthatexposevirtualmethods.Formoredetails,seethetablesofcomparisonsinthefollowingtopicComparisonofInterceptionTechniques.
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
objectisnotabaseclass,youcanonlyproxyinterfacemethods.TheTransparentProxyprocessismuchslowerthanaregularmethodcall.
InterfaceInterceptor
Allowsinterceptiononanyobjectthatimplementsthetargetinterface.ItismuchfasterthantheTransparentProxyInterceptor.
Itonlyinterceptsmethodsonasingleinterface.Itcannotcastaproxybacktothetargetobject'sclassortootherinterfacesonthetargetobject.
VirtualMethodInterceptor
CallsaremuchfasterthantheTransparentProxyInterceptor.
Interceptiononlyhappensonvirtualmethods.Youmustsetupinterceptionatobjectcreationtimeandcannotinterceptanexistingobject.
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
classescontainingpolicypipelines.Itdoesnotprovideinterceptionforclassconstructors.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UsingInterceptioninApplications
ThistopicdescribeshowtouseUnityinterceptioninyourapplications.YoucanuseUnityinterceptionwithadependencyinjection(DI)containerorasastand-alonefeaturewithnoDIcontainer.
WhenyouuseaDIcontainer,thecontainerprovidesareferencetotheinterceptedobject.Whenthecontainerresolvesanobjectthatisconfiguredforinterception,theobjectisinterceptedasdefinedintheconfiguration.Whenperformingstand-aloneinterception,youmustalreadyhaveareferencetotheobjectyouwantintercepted.Youinvokethestand-aloneinterceptionAPIandexplicitlyintercepttheobject.Formoreinformationonusingcontainers,seeDependencyInjectionwithUnity.
Unityinterceptionrequiresaninterceptor,andacollectionofinterception
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.
InterceptionwithaContainerdescribesinterceptionwithacontainer.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
Stand-AloneInterceptionwithaProxy
Stand-aloneInterceptionwithaDerivedTypeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
MicrosoftEnterpriseLibrary5.0
InterceptionwithaContainer
TheUnitycontainerextensionenablesyoutoconfigureacontainerforinterception.Youcanusethecontainerconfigurationtodeterminewhetheranobjectshouldbeintercepted,whichmechanismshouldbeusedtoperformtheinterception,andwhattodowhentheobjectisintercepted.ItalsoprovidesaconvenientsetofmethodsforconfiguringinjectionforMicrosoft.Practices.Unity.InterceptionExtension.RuleDrivenPolicyinstances.
FormoreinformationaboutconfiguringacontainerseeConfiguringaContainerforInterceptionandConfiguringUnity.
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
andcontainerswithinterception:ProcessFlowforInterceptionUsingPolicyInjectionUsingtheBuilt-InPolicyInjectionBehaviorInterceptionPoliciesMatchingRulesCallHandlersandPolicyInjectionMoreInformation
ProcessFlowforInterceptionUsingPolicyInjection
UsingtheBuilt-InPolicyInjectionBehavior
InterceptionPolicies
MatchingRules
CallHandlersandPolicyInjection
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
MatchingRule specifiedtype.
TagAttributeMatchingRule
SelectsclassmembersthatcarryaTagattributewiththespecifiedname.
TypeMatchingRule
Selectsclassesthatareofaspecifiedtype.
Thefollowingsectionsdescribethebuilt-inmatchingrulesindetail:TheAssemblyMatchingRuleTheCustomAttributeMatchingRuleTheMemberNameMatchingRuleTheMethodSignatureMatchingRuleTheNamespaceMatchingRuleTheParameterTypeMatchingRuleThePropertyMatchingRuleTheReturnTypeMatchingRuleTheTagAttributeMatchingRuleTheTypeMatchingRule
Youcanalsocreateandusecustommatchingrules.Formoreinformation,seeCreatingPolicyInjectionMatchingRules.Forinformationaboutusinginterception,seeUsingInterceptionandPolicyInjection.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheAssemblyMatchingRule
Theassemblymatchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedontheassemblynameorbyspecifyingareferencetoanassembly.
BehavioroftheAssemblyMatchingRule
CreatinganAssemblyMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheCustomAttributeMatchingRule
Thecustomattributematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonacustomattributetypethatisappliedtoclassmembers.
BehavioroftheCustomAttributeMatchingRule
CreatingaCustomAttributeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheMemberNameMatchingRule
Themembernamematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthenameoftheclassmembers(methodsorproperties),andallowsyoutousewildcardcharactersforthemembername.
BehavioroftheMemberNameMatchingRule
CreatingaMemberNameMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheMethodSignatureMatchingRule
Themethodsignaturematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthenameandsignature(thelistofparametertypes)ofitsmembers.Thisruleallowstheuseofwildcardcharactersforthemembernames.
BehavioroftheMethodSignatureMatchingRule
CreatingaMethodSignatureMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheNamespaceMatchingRule
Thenamespacematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedontheirnamespace,usingwildcardcharactersforthechildnamespacenamesbutnotfortherootnamespacename.
BehavioroftheNamespaceMatchingRule
CreatingaNamespaceMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheParameterTypeMatchingRule
Theparametertypematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthetypenameofaparameterforamemberofthetargetobject.
BehavioroftheParameterTypeMatchingRule
CreatingaParameterTypeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ThePropertyMatchingRule
Thepropertymatchingruleallowsdevelopers,operators,andadministratorstoselectindividualpropertiesofthetargetclassesbasedontheirname,includingusingwildcardcharacters,andthecombinationofaccessorstheyimplement.
BehaviorofthePropertyMatchingRule
CreatingaPropertyMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheReturnTypeMatchingRule
Thereturntypematchingruleallowsdevelopers,operators,andadministratorstoselecttargetclassesbasedonthetypeorthetypenameofthereturnvalue,usingwildcardcharactersifrequired.
BehavioroftheReturnTypeMatchingRule
CreatingaReturnTypeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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
CopyCode
CopyCode
...propertyimplementationhere...
EndProperty
EndClass
Thefollowingcodeshowsataggedclass.C#
[Tag("MyClassTagName")]
publicclassAnnotatedWithTagOnClass
{
...classimplementationhere...
}
VisualBasic
<Tag("MyClassTagName")>_
PublicClassAnnotatedWithTagOnClass
...classimplementationhere...
EndClass
BehavioroftheTagAttributeMatchingRule
CreatingaTagAttributeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheTypeMatchingRule
Thetypematchingruleallowsdevelopers,operators,andadministratorstospecifythetargetclassusingthenamespaceandclassnameofthetargettype.
BehavioroftheTypeMatchingRule
CreatingaTypeMatchingRuleatRunTimeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
PolicyandHandlerPrecedencewithAttributes
ExampleofanAttribute-DrivenPolicyToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
EnterpriseLibraryCallHandlers
Thepatterns&practicesEnterpriseLibraryincludesasetofcallhandlersandtheequivalentcallhandlerattributesdesignedforusewiththeUnityPolicyInjectionBehavior.ThissectiondiscussessomeofthecommonscenariosforusingthePolicyInjectionApplicationBlockcallhandlers.Itexaminesthefollowingcommonscenarioswheretheblockcansimplifyandaccelerateapplicationdevelopment:
LoggingMethodInvocationandPropertyAccessHandlingExceptionsinaStructuredMannerValidatingParameterValuesAuthorizingMethodandPropertyRequestsMeasuringTargetMethodPerformance
LoggingMethodInvocationandPropertyAccess
HandlingExceptionsinaStructuredManner
ValidatingParameterValues
AuthorizingMethodandPropertyRequests
MeasuringTargetMethodPerformance
MoreInformationToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheAuthorizationHandler
Theauthorizationhandlerprovidesthecapabilitytocheckthatthecurrentuser(thesecurityprincipalforthecurrentthread)hastherequisitepermissiontoaccesstheselectedobjectmethodorproperty.ThishandlerusestheSecurityApplicationBlockandtakesadvantageofthefeaturesthatitexposes.
Theauthorizationhandlerappliesthesecuritycheckbeforeinvocationoftheselectedmethodorsettingoftheselectedpropertyofthetargetobject.Ifthecurrentuserdoesnothavepermissiontoaccessthemethodorpropertyaccessor,theauthorizationhandlerabortsexecutionduringthepreprocessingstageanddoesnotinvokethetargetmethodorsetthetargetproperty.ItalsogeneratesanUnauthorizedAccessExceptionandpackagesitintothemessagepassedbacktotheprevioushandlerinthepipeline.
Note:ThiscallhandlerisimplementedintheMicrosoft.Practices.EnterpriseLibrary.Security.PolicyInjectionnamespaceoftheSecurityApplicationBlockintheMicrosoft.Practices.EnterpriseLibrary.Security.dllassembly.
BehavioroftheAuthorizationHandler
CreatingInstancesoftheAuthorizationHandler
UsingtheAuthorizationHandlerAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
BehavioroftheExceptionHandlingHandler
CreatingInstancesoftheExceptionHandlingHandler
UsingtheExceptionHandlingHandlerAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
BehavioroftheLoggingHandler
CreatingInstancesoftheLoggingHandler
UsingtheLoggingHandlerAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
ThePerformanceCounterHandler
Theperformancecounterhandlerincrementsaspecificcountereachtimeitexecutesinresponsetoinvocationoftheselectedmethodorsettingoftheselectedproperty.ThishandlerusestheinstrumentationfeaturesthatarepartoftheEnterpriseLibraryCore.
Theperformancecounterhandlerappliesbothbeforeandafterinvocationoftheselectedmethodoraccesstotheselectedpropertyofthetargetobject.Thehandlercanincrementdifferenttypesofcountersandincrementmorethanonecountereachtime(suchasasingleinstanceandatotalcounter).
Note:ThiscallhandlerisimplementedintheMicrosoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlersnamespaceoftheMicrosoft.Practices.EnterpriseLibrary.PolicyInjection.dllassembly.
InstallingandRemovingPerformanceCounters
BehaviorofthePerformanceCounterHandler
CreatingInstancesofthePerformanceCounterHandler
UsingthePerformanceCounterHandlerAttributeToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
TheValidationHandler
Thevalidationhandlerprovidesthecapabilitytotestwhetherthevalueprovidedfortheselectedproperty,orthevaluesspecifiedfortheparametersoftheselectedmethod,arevalidagainstspecificrules.ThishandlerusestheValidationApplicationBlock,takingadvantageofthewiderangeofcapabilitiesthatitoffers.
Thevalidationhandlerappliesthevalidationbeforeinvokingthemethodorsettingthepropertyofthetargetobject.Ifvalidationfails,thevalidationhandlerabortsexecutionofthepreprocessinghandlerpipeline,doesnotinvokethemethodorsettheproperty,andraisesanArgumentValidationException.
Note:ThiscallhandlerisimplementedinMicrosoft.Practices.EnterpriseLibrary.Validation.PolicyInjectionnamespaceoftheValidationApplicationBlock,intheassemblyMicrosoft.Practices.EnterpriseLibrary.Validation.dll.
BehavioroftheValidationHandler
CreatingInstancesoftheValidationHandler
UsingtheValidationHandlerAttribute
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
DesignofUnity
Thistopicdescribesthedesigngoals,thearchitecture,andthedesignhighlightsofUnity.YoudonothavetounderstandthedesigntouseUnity;however,thistopicwillhelpyoutounderstandhowitworksandhowitinteractswiththeunderlyingObjectBuildersubsystem.
DesignGoals
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
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.
MicrosoftEnterpriseLibrary5.0
CreatingandUsingContainerExtensions
YoucancreateyourowncustomUnitycontainerextensions,orusecontainerextensionscreatedbythirdpartieswithUnity.Unityusesdefaultcontainerextensionstoimplementitsownfunctionality.Forexample,theinterceptionmechanismprovidedbyUnityisimplementedasacontainerextension.
DocumentationtohelpyouunderstandObjectBuilder,andthestepsrequiredtocreatecustomcontainerextensions,isavailablefromtheUnityCommunityWebsiteonCodePlex.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
Example:TheTagAttributeMatchingRuleToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
CreatingInterceptionPolicyInjectionCallHandlers
Tocreateacallhandlerforpolicyinjection,youmustunderstandthewaythatUnitypassescallsthroughthepolicypipeline.Thistopicexplainshowthepipelineexecutescallhandlers,andhowitcanblockorabortexecutionwhenanerroroccurs,orondemand(suchaswhenavalidationhandlerdetectsavalidationerrororanauthorizationhandlerdetectsanunauthorizeduser).Thistopiccontainsthefollowingsections:
TheICallHandlerInterfaceandPipelineExecutionOutlineImplementationofaCallHandlerExceptionsandAbortedPipelineExecution
TheICallHandlerInterfaceandPipelineExecution
OutlineImplementationofaCallHandler
ExceptionsandAbortedPipelineExecutionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
'''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.
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
<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.
MicrosoftEnterpriseLibrary5.0
CreatingInterceptionBehaviors
UnityusestheInterceptorclasstospecifyhowinterceptionhappens,andtheInterceptionBehaviorclasstodescribewhattodowhenanobjectisintercepted.Unityinterceptionutilizesabehaviorpipelinetoforthebehaviors.TheInterceptionBehaviorPipelinemaintainsalistofinterceptionbehaviorsandmanagesthem,callingthemintheproperorderwiththecorrectinputs.
ForinformationonthedetailsaboutinterceptionbehaviorsseeInterceptionwithUnityandBehaviorsforInterception.
Toprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
UsingXCopy
VersioningToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
MicrosoftEnterpriseLibrary5.0
UpdatingtheUnityAssemblies
IfanupgradedversionofUnitybecomesavailable,youcaninstallthenewversionandhaveallapplicationsusetheupdatedassembly.However,ifthenewversionintroducescompatibilityproblemsforcertainapplications,youcaninstallthenewversionintheglobalassemblycacheandconfiguresomeapplicationstousetheupdatedversion,whileotherscontinuetousetheearlierversion.
UpdatingPrivateAssemblies
UpdatingSharedAssembliesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
UsingVisualStudiotoStrongNametheUnityAssembliesToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
UnityQuickStarts
TheinstructionsinthisQuickStarttopicaredirectedattheSilverlightsolution.Thoughtherearemanysimilarities,someinstructionsinthistopic,suchasreferencestoProgram.csorProgram.vb,donotapplytotheSilverlightproject.ThefollowingQuickStartapplicationsdemonstratesomeofthekeyfeaturesofUnity:
Walkthrough:TheUnityStopLightQuickStart.ThisQuickStartdemonstratesdependencyinjectiontechniques.ThisistheonlyQuickStartprojectintheSilverlightsolution.Walkthrough:TheUnityEventBrokerExtensionQuickStart.ThisQuickStartprovidesanexampleextensionfortheUnitycontainer.TheSilverlightsolutiondoesnoincludetheEventBrokerQuickStart.
Note:UnityQuickStartsareonlyavailableifyouinstallthestandaloneUnityMSI.TheUnityMSIisavailableatpatterns&practices-UnityonCodePlex.
BuildingtheQuickStartsToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
MicrosoftEnterpriseLibrary5.0
Walkthrough:TheUnityStopLightQuickStart
TheStopLightQuickStartdemonstratesthewaysthatyoucanuseUnityandtheUnitycontainerinyourapplications.TheuserinterfaceisasimpleWindowsFormsapplicationthatdisplaysthethreecolorsofastoplightortrafficlight—itshowsred,yellow,andgreen,inturn,forspecifiedperiods.Youcanconfigurethedisplayperiodsforeachcolor.Thefollowingillustrationshowstheuserinterface.
TheStopLightQuickStartdemonstratesthefollowingfeaturesofUnity:RegisteringmappingsfortypeswiththecontainerImplementingtheModelViewPresenterpatternbyinjectingapresenterintotheuserinterfaceInjectingabusinesscomponentintoobjectsusingproperty(setter)injectionImplementingaconfigurablepluggablearchitecture
ThefollowingdiagramshowstheclassesandarchitectureoftheStopLightQuickStartapplication.
RegisteringMappingsforTypeswiththeContainer
ImplementingtheModel-View-PresenterPattern
InjectingaBusinessComponentusingProperty(Setter)Injection
ImplementingaConfigurablePluggableArchitectureToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.
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.
IfyoucomparethisdiagramtothestructureoftheStopLightQuickStartshowninWalkthrough:TheUnityStopLightQuickStart,youcanseethattheEventBrokerExtensionQuickStarthasthefollowingadditionalfeatures:
TheProgramclass,whichregistersthetypemappingsinthecontainerandcallstheResolvemethodtoinstantiatethemainStopLightform,alsoaddstheSimpleEventBrokerExtensiontothecontainer.TheSimpleEventBrokerExtension,whichinheritsfromtheUnityContainerExtensionbaseclass,createsaninstanceoftheEventBrokerclassthatimplementsthepublishandsubscribepatternfordistributedevents.TheEventBrokerclasscreatesaninstanceofthePublishedEventclassthatprovidesthefacilitiesformaintainingalistofeventsubscriptionsandraisingeventstoregisteredsubscribers.TheStopLightPresenter,StopLightSchedule,andRealTimeTimerclassesincludeattributesthatregistereventpublicationsandsubscriptionswiththeSimpleEventBrokerExtensionclass.
TheEventBrokerExtensionQuickStartdemonstratesthefollowingfeaturesofUnityandthecustomcontainerextensionmechanism:
CreatingthecustomUnitycontainerextensionAddinganextensiontotheUnitycontaineratruntimeUsingtheexampleEventBrokerExtension
CreatingaCustomUnityContainerExtension
AddinganExtensiontotheUnityContaineratRunTime
UsingtheExampleEventBrokerExtensionToprovidefeedback,getassistance,ordownloadadditionalcontent,pleasevisittheEnterpriseLibraryCommunityWebsite.Toreportdocumentationerrorsorprovidefeedbackonthisdocumentation,[email protected].
Copyright©2010byMicrosoftCorporation.Allrightsreserved.