Write Less Code and Play More Golf—Getting to Know Enterprise Library 4.0

patterns & practices Developer Center

patterns & practices Developer Center
Alex Homer, Microsoft Corporation
August 2008

This article provides an overview of Microsoft Enterprise Library. It discusses why you should consider using this useful set of routines and components in your applications, what Enterprise Library actually is, and how you can get started using it.

Contents

Why Build From Scratch?
The Enterprise Library Candy Store
A Brief History of Enterprise Library
What Do I Get in Enterprise Library?
Getting Started with Enterprise Library
Extending and Modifying Enterprise Library
Conclusion

For more information about Enterprise Library, see the Enterprise Library Web site on CodePlex. To download Enterprise Library, see Enterprise Library on MSDN (https://msdn.microsoft.com/entlib).

Why Build From Scratch?

Imagine for a moment that you have decided to build your own sports car. None of the car dealers has anything that you really fancy driving, so the plan is to create the perfect car in your own backyard. After spending a few days with a sketch pad, you have worked out the perfect raking roofline, the graceful curving wheel arches, and the fine detail of the front grille. You also know what the basic structure and layout will be—it will have two doors, four wheels, and be mid-engined. So, you get to work with the welding gear and fiberglass, and after a few days you have the best looking car ever.

Of course, so far it is just a body shell; you now need to source the running gear, interior fittings, electrical equipment, and the rest of the myriad bits of kit that make up a modern motor car. So where do you start? By turning a set of pistons on the lathe in your workshop? By soldering up a circuit board for the engine management system? By rolling some steel sheet to make an exhaust system? Of course not—you dig out the parts supplier catalogs, cruise the Web, and order up the ready-built engine, gearbox, interior fittings, and all the other systems you need.

So why is it that many software developers refuse to follow this obvious course of action and, instead, insist on building every component and service they need from scratch? Okay, so they may start by sketching out the body of the application, and the overall structure and layout of the component parts, but then they set to creating custom data access layers, validation components, exception management systems, cryptography routines, and security management code.

The point is that, like the components of a motor car, most of this "stuff" is common across your applications and everybody else's applications. With modern plug-in architectures, dependency injection mechanisms, and standardization of the platform (providing, in this instance, that you are using the .NET Framework), you can reduce your development time and effort, simplify the code, and minimize testing resources by using tried and tested routines and components that are easily available. And, even better in the case of Enterprise Library, are free.

The Enterprise Library Candy Store

The overall aim of the patterns & practices team at Microsoft is to make it easier to use Microsoft products to build applications and systems. They achieve this by providing software tools, software factories, utilities, and code libraries; plus guidance such as Help files, online documents, videos, and useful information in many other guidance formats.

One of the key products in the patterns & practices range is the Enterprise Library. This is a set of application blocks, core utilities and routines, and associated guidance that can simplify and speed up development of almost any type of application. Enterprise Library demonstrates best practice coding techniques, is generic and extensible, and free for you to use, modify, and distribute as part of your applications. It implements reusable code routines that make it easier to include in your applications features such as data access, logging, caching, validation, exception handling, cryptography, security credential management, policy injection, and dependency injection.

Yet many people take one look at Enterprise Library and are frightened off. Yes, there are a lot of features, a great deal of code, and more than 900 pages of documentation. At first glance, it may seem somewhat intimidating. I hear the same questions over and over again when I talk to developers and architects at conferences and user group meetings: "How long will it take to figure out what I need and then learn how to use it?", "Why does it seem so complicated?", and "Do I really want all those assemblies that I'm not using in my application?".

The response to all these kinds of questions is that you only need to use the features that are relevant. You don't have to include all the assemblies, you don't have to understand all of the code, and you don't have to write custom extensions unless you have relatively unusual requirements. You can treat Enterprise Library like one of those "pick & mix" candy store counters. You start by picking up a bag, and you are free to choose which, and how many of each, of the range of tempting items to get. With Enterprise Library, you include in your application the core features common to all the application blocks, and then you add just the specific features and the relevant assemblies that you need to implement the required functionality.

These assemblies are quite small (most are less than 200 KB, and many are less that 50 KB), and are digitally signed so that you can simply drop them into the bin folder of your application or install them in the global assembly cache if you prefer. In version 4.0 of Enterprise Library, the assemblies can be used as they are in partial trust environments such as Web Forms applications. In addition, if you decide to extend the features of an application block, you can usually do so without requiring recompilation of the original code—you simply write your custom providers as plug-ins that use the built-in extensibility points.

A Brief History of Enterprise Library

The foundations of Enterprise Library were laid several years ago with the individual application blocks, such as the User Interface Process Application Block, the Exception Handling Application Block, and (probably the best known) the Data Access Application Block. The major failing with these application blocks was the complexity of configuring them. You had to manually edit the XML configuration file—a process that made many developers decide Enterprise Library was just too difficult to consider. In addition, each application block had to contain core routines that were common across all the application blocks, such as code to perform serialization, handlers for the custom configuration sections, and code to instantiate instances of the objects used by the application block.

The obvious answer was to combine all the application blocks into a single library, and extract the common code into a separate core assembly. This reduced the code required in each application block and standardized the core routines and the overall coding approach. More important, the library could now include a comprehensive and easy to use configuration tool that meant developers no longer had to fight with an XML file in a text editor. The configuration tool (now also provided as a plug-in to Visual Studio) makes it easy to see what configuration settings are required, automatically adds application block dependencies, and validates settings as you edit the configuration.

Since version 1.0, Enterprise Library has grown to include new application blocks with each major release, has improved performance, and has added features requested by developers to the core and to each of the application blocks. These added features include full instrumentation that allows you to see what is happening inside the application block as you execute the code, a wider range of extension points for custom providers and plug-ins, improved documentation, better support for partial trust environments, and manageability extensions to make it easier to build applications that interact with Group Policy and Windows Management Instrumentation (WMI).

In the latest version, 4.0, Enterprise Library now includes a comprehensive mechanism for implementing the Inversion of Control (IoC) and Dependency Injection design patterns, including support for using these patterns to inject Enterprise Library objects into your application classes and components.

What Do I Get in Enterprise Library?

In version 4.0, Enterprise Library contains nine application blocks, the core code that implements common functionality, QuickStart sample applications for each application block, batch files and utilities to set up Enterprise Library and the QuickStarts, a full set of unit tests, and comprehensive documentation. In addition, at the Enterprise Library Web site on CodePlex, you can download add-ins, providers, and other resources contributed and shared by the community.

The following nine application blocks are included in the Enterprise Library version 4.0:

  • Caching Application Block. Developers can use this application block to incorporate local (and, with a plug-in provider, distributed) caching capabilities in their applications.
  • Cryptography Application Block. Developers can use this application block to incorporate hashing and symmetric encryption in their applications.
  • Data Access Application Block. Developers can use this application block to incorporate standard database functionality in their applications.
  • Exception Handling Application Block. Developers can use this application block to create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.
  • Logging Application Block. Developers can use this application block to include standard logging functionality in their applications.
  • Policy Injection Application Block. Developers can use this application block to implement interception policies that streamline the implementation of common features, such as logging, caching, exception handling, and validation, across an application.
  • Security Application Block. Developers can use this application block to incorporate authorization and security caching functionality in their applications.
  • Unity Application Block. Developers can use this application block to implement a lightweight, extensible dependency injection container with support for constructor, property, and method call injection.
  • Validation Application Block. Developers can use this application block to create validation rules for business objects that can be used across different layers of their applications.

Getting Started with Enterprise Library

Getting to know Enterprise Library is not a quick process. There is a huge amount of functionality in there, and getting it wrong when you start could mean that you fail to get the best from it or even give up before you have a chance to see the benefits it provides. This section describes the recommended stages for getting started with Enterprise Library and includes the following topics:

  • Using the Documentation and Hands-On-Labs
  • Installing and Configuring Enterprise Library
  • Using the Application Blocks in Your Applications

Using the Documentation and Hands-On-Labs

We are all aware that we should read the manual before starting to use any complex piece of equipment or software. Although "poke and play" is the approach most commonly used by many developers to discover capabilities, it really is a good idea to spend a little time with the Enterprise Library documentation when you first start. This will help you to understand when it is appropriate to use each application block, the kinds of situation it is most suited to, and the issues to be aware of when using it.

The documentation begins with four main sections that provide an introduction, recommendations for getting started, general advice on how to develop applications that use Enterprise Library, and the design of Enterprise Library. These are all useful, but they can be a little overwhelming when you just want to get some code running. However, they are essential reading as you become more familiar with Enterprise Library, and they explain many of the concepts that are common to all of the application blocks.

To help you get to know each of the applications blocks individually, there is a separate section devoted to each one. These sections intentionally follow the same format and structure. The sections include the following:

  • A section that introduces essential features of the application block.
  • A section that provides specific details about how to develop applications using the application block.
  • A section that provides a set of key scenarios and the code to implement a solution for each one.
  • A section that provides notes about the design of the application block.
  • A section that provides details of how you can extend and modify the application block.
  • A section that provides information about deploying the application block and using the instrumentation.
  • A section that provides walkthroughs of the QuickStart example(s).

In addition, there are hands-on labs that you can work through and QuickStart examples you can run for each application block. Therefore, when familiarizing yourself with Enterprise Library, the best way to begin is by reading the "Introduction" topic for each application block. This topic contains the following:

  • It contains a list of the common scenarios for the application block.
  • It contains short examples of the application code required to use the application block.
  • It contains the highlights of the application block.
  • It contains notes to help you determine when to use (and when not to use) this application block.
  • It contains alternatives to using this application block.
  • It contains additional notes about the application block, such as security considerations for caching and selecting an appropriate cryptography algorithm.

Reading the "Introduction" topic helps you decide whether the application block suits your requirements, as well as giving you a head start to using the application block, and at the same time, you can work through the hands-on labs and run the QuickStart examples to see how you actually use the application block, and what you can achieve with it.

Installing and Configuring Enterprise Library

Enterprise Library is supplied as a Window Installer package (an .msi file) that installs the assemblies, tools, and other artifacts required to use the library. You can optionally choose to install the documentation and the full source code. When you install the source code, the installer will also offer to compile it for you. It is a good plan to install and compile the source code unless you never intend to extend or modify the library.

To use Enterprise Library in your applications, you must configure the application blocks you want to use. The default configuration mechanism uses file-based configuration sections located in the Web.config, App.config, or other configuration file for your application. The configuration tools will automatically modify your configuration file, adding the section handlers and the configuration information required for each application block. As you add each application block, the tools set a default configuration that represents the most common requirements. In addition, if you specify a provider that requires the services of another application block, the tools will add the dependent application block with its default settings.

For example, if you add the Caching Application Block to your application and specify the Data Cache Provider (which stores the cached data in a database), the configuration tool automatically adds the Data Access Application Block, as shown in Figure 1.

Ff648712.97038ed4-5182-4dc8-aae5-f85745e4c475(en-us,PandP.10).png

Figure 1
The Enterprise Library Configuration Console showing the Caching Application Block and the Data Access Application Block

Alternatively, you can configure the application blocks using the configuration API by generating instances of .NET-connected configuration objects and then instantiating the application block items with this configuration object. Some of the application blocks also allow you to dynamically change the configuration at run time.

Configuration Sources

Although the default configuration resides in Web.config or App.config and uses the default system configuration source, you can use a different configuration source if you want. You can store your configuration in a separate file using the file configuration source, or integrate the configuration system with Group Policy and WMI using the manageable configuration source. In addition, the source code for Enterprise Library contains a QuickStart example that implements a SQL configuration source. You can use this to store your configuration in a database, or you can modify it to store your configuration data elsewhere.

Almost every feature of Enterprise Library and the individual application blocks are configurable, which makes it easy to change the behavior of an application without requiring you to edit the code, recompile it, or install updated versions of your application. This illustrates the real power of Enterprise Library; for example, you can change an application that uses an OLE-DB database to use SQL Server (through the Tabular DataStream interface) simply by changing the configuration settings.

In addition, if you configure more than one provider or feature of an application block, you can specify in the configuration which of these is the default provider for your application to use if it does not directly specify one of the providers. Then, to change the application's behavior, you just change the default setting in the configuration.

Enterprise-level applications should support management features. For example, they should take account of Group Policy settings and expose both configuration and event information through WMI. The manageable configuration source makes it easy to add this feature to your applications, allowing administrators to change the behavior of your application from a central location, monitor events and performance of the application, and even change the live configuration using WMI tools.

Block Dependencies

Figure 2 shows the possible dependencies for the Enterprise Library application blocks when you use the various providers available for each application block. You can see that, for example, the Policy Injection Application Block may depend on several other application blocks. If you use the Logging Handler in the Policy Injection Application Block, it uses the services of the Logging Application Block. Likewise, the Exception Handling Handler uses the Exception Handling Application Block, the Authorization Handler uses the Security Application Block, and the Validation Handler uses the Validation Application Block.

Ff648712.7c666661-8b13-41d5-a4be-b3d976cc3e6a(en-us,PandP.10).png

Figure 2
The application block dependencies when using the default object creation mechanism

Each application block consists of one main assembly that you install when you want to use that application block, plus small additional assemblies for some of the plug-in providers. The only other requirements are the assembly containing the core functions (not required for the Unity Application Block) and the ObjectBuilder2 assembly that implements the generic object factory used by all the application blocks.

The following table lists the main runtime assemblies for each application block and the assemblies that implement optional additional features. For example, if you want to take advantage of the user interface controls provided with the Validation Application Block to provide validation feedback to uses in an ASP.NET page, you must include with your application the assembly named Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet.dll. Signed versions of all these assemblies are provided in the main bin folder of the Enterprise Library installation.

Block

Assembly name

Description

Caching

Microsoft.Practices.EnterpriseLibrary.Caching.dll

Core application block features

Microsoft.Practices.EnterpriseLibrary.Caching.Database.dll

Data Caching Store provider

Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.dll

To encrypt cached data

Data

Microsoft.Practices.EnterpriseLibrary.Data.dll

Core application block features

Microsoft.Practices.EnterpriseLibrary.Data.SqlCe.dll

SQL Server CE provider

Exception handling

Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll

Core application block features

Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll

To log exceptions

Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.dll

Integration with Windows Communication Foundation (WCF)

Logging

Microsoft.Practices.EnterpriseLibrary.Logging.dll

Core application block features

Microsoft.Practices.EnterpriseLibrary.Logging.Database.dll

To log to a database

Policy injection

Microsoft.Practices.EnterpriseLibrary.PolicyInjection.dll

Core application block features

Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.dll

Call handlers

Security

Microsoft.Practices.EnterpriseLibrary.Security.dll

Core application block features

Microsoft.Practices.EnterpriseLibrary.Security.Cache.CachingStore.dll

Cache for credentials

Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll

To encrypt cached data

Unity

Microsoft.Practices.Unity.dll

Core application block features

Microsoft.Practices.Unity.Configuration.dll

Configuration handler

Validation

Microsoft.Practices.EnterpriseLibrary.Validation.dll

Core application block features

Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet.dll

Integration with ASP.NET

Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF.dll

Integration with WCF

Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WinForms.dll

Integration with Windows Forms

Note

Notice that the Unity Application Block is not included the Figure 2, even though it is part of Enterprise Library. Unity is designed for stand-alone use; because of this, it has no dependencies on other application blocks by default. It does not use the core Enterprise Library configuration system; instead, it uses its own separate configuration handler (as shown in the previous table). If you do not want to read configuration data into a Unity container, you do not require the configuration assembly.
For more information about the way that Unity integrates with Enterprise Library, see Creating Objects Using the Unity Application Block on MSDN.

Using the Application Blocks in Your Applications

After you add Enterprise Library to your application and set the required configuration, you will probably want to reference the application block namespaces to make it easier to write code. This section explains how to reference the application block namespaces, and then it continues by exploring how you can use the objects exposed by the application blocks to achieve the functionality you require.

Referencing the Application Blocks in Your Code

To use the Enterprise Library application blocks in your applications, you must reference the required assemblies in your project. You can do the following:

  • You can copy the assemblies into your application's **bin **folder.
  • You can install the assemblies in the global assembly cache and reference them using the .NET tabbed page of the Visual Studio References dialog box.
  • You can install the assemblies in another folder and reference them using the Browse tabbed page of the Visual Studio References dialog box.

You should also add the appropriate using (C#) or Imports (Visual Basic) statements at the top of your code in Visual Studio for the namespaces containing the components you will directly reference. Some of the assemblies contain more than one namespace. For example, the main Logging Application Block assembly contains twelve namespaces, including the following:

  • Microsoft.Practices.EnterpriseLibrary.Logging
  • Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation
  • Microsoft.Practices.EnterpriseLibrary.Logging.Filters
  • Microsoft.Practices.EnterpriseLibrary.Logging.Formatters
  • Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation
  • Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners

However, you do not have to import a namespace unless you actually reference the objects contained in them in your code.

Creating and Using Application Block Features

The Enterprise Library application blocks fall into two main categories with respect to the way you use the objects they contain. Some application blocks implement a façade against which you write code. Others contain a factory class with a static method that creates objects you use in your code. Some contain a mixture.

In addition, as of version 4.0 of the Enterprise Library (which added the Unity Application Block to Enterprise Library) the recommended way to instantiate Enterprise Library objects is changing. Many of the application blocks now include a special Unity container extension you can use to instantiate objects in the application block through the Unity container. This will be the officially recommended way to instantiate Enterprise Library objects in future releases. However, you really should consider adopting this approach now with the application blocks that support it.

The following sections show the most common scenarios for using the application blocks and the features they implement.

Application Blocks with a Static Façade

The following list shows the application blocks that implement a static façade:

  • The Cryptography Application Block contains the** Cryptographer** façade, which exposes static methods such as CreateHash and EncryptSymmetric.
  • The Exception Handling Application Block contains the **ExceptionPolicy **façade, which exposes the static **HandleException **method.
  • The Logging Application Block contains the Logger façade, which exposes static methods such as Write and IsLoggingEnabled.
  • The Validation Application Block contains the **Validation **façade, which exposes static methods such as **Validate **and ValidateFromAttributes.

The following code shows how you can use the façades implemented by these application blocks. The first example uses the Cryptography Application Block and assumes that you have configured a symmetric provider. The static EncryptSymmetric method accepts the name of the configured provider and the data to encrypt. It returns the encrypted value as a string.

'Usage

Dim encryptedContentsBase64 As String _
    = Cryptographer.EncryptSymmetric("provider-name", "data-to-encrypt")
string encryptedContentsBase64 
    = Cryptographer.EncryptSymmetric("provider-name", "data-to-encrypt");

The second example uses the Validation Application Block and assumes that you have configured a rule set for the Customer class. The Validate method returns an instance of the ValidationResults class that contains information about validation failures.

'Usage

Dim cust As New Customer()
Dim results As ValidationResults _
    = Validation.Validate(Of Customer)(cust, "ruleset-name")
Customer cust = new Customer();
ValidationResults results 
    = Validation.Validate<Customer>(cust, "ruleset-name");

Application Blocks with Object Factory Classes

The following application blocks contain a factory for creating object instances:

  • Caching Application Block. This application block contains the CacheFactory class that exposes the static GetCacheManager method for creating a CacheManager that you use to manipulate the cache.
  • Data Access Application Block. This application block contains the **DatabaseFactory **class that exposes the static **CreateDatabase **method for creating a Database instance that you use to manipulate a database.
  • Security Application Block. This application block contains two factory classes. The **AuthorizationFactory **class exposes the static GetAuthorizationProvider method that generates an authorization provider, while the SecurityCacheFactory class exposes the static GetSecurityCacheProvider method that generates a credentials cache.

The following code shows how you can use the façades implemented by these application blocks. The first example uses the Data Access Application Block and assumes that you have configured a connection string that specifies a database provider. The code creates a command to execute a stored procedure, adds a parameter, and executes the command to return a populated Dataset instance.

'Usage

Dim db As Database = DatabaseFactory.CreateDatabase("connection-string-name")
Dim dbCommand As DbCommand = db.GetStoredProcCommand("GetProductsByCategory")
' Retrieve products from the category 7.
db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, 7)
Dim productDataSet As DataSet = = db.ExecuteDataSet(dbCommand)
Database db = DatabaseFactory.CreateDatabase("provider-name");
DbCommand dbCommand = db.GetStoredProcCommand("GetProductsByCategory");
// Retrieve products from category 7.
db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, 7);
DataSet productDataSet = db.ExecuteDataSet(dbCommand); 

If you specify a default database in the configuration, you can omit the name when you create the object instance. For example, you can create a Database instance using the following code.

'Usage

Dim db As Database = DatabaseFactory.CreateDatabase()
Database db = DatabaseFactory.CreateDatabase();

This means that you can change the provider that the application block uses simply by changing the setting of the Default property for the application block in the configuration.

The second example uses the Security Application Block and assumes that you have configured an authorization provider. It creates a user credential as a GenericPrincipal instance, creates an instance of the configured authorization provider, and tests whether the user is authorized to perform the "Print Document" action by calling the Authorize method.

'Usage

Dim principal As IPrincipal _
    = New GenericPrincipal(New GenericIdentity("Username"), New String() {"Manager"})
Dim ruleProvider As IAuthorizationProvider _
    = AuthorizationFactory.GetAuthorizationProvider("provider-name")
Dim authorized As Boolean = ruleProvider.Authorize(principal, "Print Document")
IPrincipal principal 
    = new GenericPrincipal(new GenericIdentity("Username"), new string[]{"Manager"});
IAuthorizationProvider ruleProvider 
    = AuthorizationFactory.GetAuthorizationProvider("provider-name");
bool authorized = ruleProvider.Authorize(principal, "Print Document"); 

Creating Instances of Enterprise Library Objects Using the Unity Container

The following table lists the application blocks in version 4.0 of Enterprise Library that contain a special Unity container extension you can use to instantiate objects in the application block through the Unity container. It also shows the replacement classes that you must use when creating objects through the Unity container, where you cannot use the existing static façade.

Application block

Existing façade

New façade for use with Unity

Data Access Application Block

   

Caching Application Block

   

Security Application Block

   

Cryptography Application Block

Cryptographer

CryptographyManager

Exception Handling Application Block

ExceptionPolicy

ExceptionManager

Logging Application Block

Tracer

TraceManager

As an example, the following code shows how you can retrieve a CacheManager instance for use in your applications.

// Get a reference to the default CacheManager as defined in the configuration.
ICacheManager cacheMgr = uContainer.Resolve<ICacheManager>();

// Get a reference to a specific named CacheManager defined in the configuration.
ICacheManager namedCacheMgr = uContainer.Resolve<ICacheManager>("MyCache");
' Get a reference to the default CacheManager as defined in the configuration.
Dim cacheMgr As ICacheManager = uContainer.Resolve(Of ICacheManager)()

' Get a reference to a specific named CacheManager defined in the configuration.
Dim namedCacheMgr As ICacheManager = uContainer.Resolve(Of ICacheManager)("MyCache")

One of the major advantages with the Unity container-based approach is that you can use dependency injection to automatically instantiate and inject instances of Enterprise Library objects into your own custom objects and application code through constructor, property (setter), and method call injection. This makes it much easier to create loosely coupled applications and implement design patterns such as Inversion of Control (IoC), Model-View-Controller (MVC), Service Locator, and more. For more information, see Creating Objects Using the Unity Application Block on MSDN.

Creating Instances of Enterprise Library Objects Directly

You can also generate instances of most of the Enterprise Library objects directly in your code. For example, you can use the new operator to create a new Tracer instance (a class in the Logging Application Block) or to create individual validators from the Validation Application Block. You can even create a custom configuration source and then use the use this to configure a new instance of an object you create. For more information, see Creating Objects Using the Provider Factory Methods on MSDN.

Extending and Modifying Enterprise Library

Enterprise Library is designed to provide functionality for specific scenarios. Each application block provides objects and methods focused on related tasks. However, all the application blocks are extensible, so that you can add new providers and other features to tailor the behavior to exactly suit your specific requirements.

For example, you can extend the Caching Application Block by creating a new cache backing store provider is you want to store the cached data in an unsupported location, or you can use a caching approach that the standard providers do not support. In some cases, you can also extend an application block by replacing core functionality with your own implementations. For example, the Caching Application Block uses an instance of the CacheManager class to manipulate, store, and retrieve cached items. You can replace the default CacheManager class with your own implementation if you need to change the way that cached items are manipulated, stored, and retrieved. For example, you may want to enable a distributed caching mechanism.

The following table lists the extension points for all the application blocks. In general, you will either implement a specific interface or derive a new class from an existing class. Again, using the Caching Application Block as an example, you can create a new cache backing store by inheriting the BaseBackingStore class to take advantage of the base features it provides, or you can create an entirely new class that implements the IBackingStore interface.

Block

Description

Extension point

Caching

Create a new provider for a custom cache backing store.

Implement IBackingStore or derive a new class from BaseBackingStore.

Create a new expiration policy for cached items.

Implement ICacheItemExpiration and ICacheItemRefreshAction.

Replace the default cache manager to implement a custom caching mechanism.

Implement ICacheManager.

Cryptography

Create a custom hash algorithm provider.

Implement IHashProvider.

Create a custom symmetric encryption algorithm provider.

Implement ISymmetricCryptoProvider.

Data Access

Create a new database provider (the ADO.NET DbProviderFactory must already support the new database type).

Derive a new class from the existing Database class.

Exception handling

Create a new exception handler class.

Implement IExceptionHandler.

Create a new exception formatter class.

Derive a new class from ExceptionFormatter.

Logging

Create a custom formatter.

Implement ILogFormatter.

Policy injection

Create a new matching rule.

Implement IMatchingRule.

Create a new call handler.

Implement ICallHandler.

Create a new call handler attribute.

Derive a new class from HandlerAttribute.

Security

Create a new authorization provider.

Derive a new class from AuthorizationProvider.

Unity

Create a new lifetime manager.

See Unity Application Block on MSDN.

Create a container extension

See Unity Application Block on MSDN.

Validation

Create a new validator.

Derive a new class from Validator.

Create a new validator attribute.

Derive a new class from ValidatorAttribute.

In addition to extending the application blocks through the extension points, you can modify the source code to change the behavior if you want. It is advisable to modify copies of the Enterprise Library source, and use a different namespace, so that you still have the original source code and functionality available.

You must then recompile the Enterprise Library to incorporate your changes. Enterprise Library includes batch files that you can run to recompile the entire source code tree, and then you copy the assemblies to the required locations. Of course, you will then have to re-sign the assemblies with your own key if you need to install them in the global assembly cache or to protect against changes to the code after deployment. You can use the Strong Naming Guidance Package to strong name your assemblies.

Finally, if you want to, you can create a completely new application block and integrate it with Enterprise Library. This is obviously more complex, but it may be useful if you need to implement specific functionality that the other application blocks do not provide. To help you get started building a new application block, you can use the Application Block Software Factory.

The Strong Naming Guidance Package and the Application Block Software Factory are available from the Enterprise Library Contrib Community on CodePlex. Download change set 18160, "Add Strong Naming guidance package and add block factory."

Conclusion

Enterprise Library provides a set of application blocks that are comprehensive, easy to use, flexible, and extensible. Together with the configuration tools and the core utilities, the library can considerably reduce development effort, time to market, and test requirements.

Much of this flexibility comes from a wide range of configuration options and settings, which you can store in a range of ways. For example, instead of the default file-based configuration system, you can use a database or any custom store. In addition, Enterprise Library configuration can integrate fully with WMI and react to overrides applied through Group Policy.

When designing and building your applications, you can choose which features and application blocks you want to use and distribute the signed assemblies as part of your application—all at no cost and with very few licensing limitations.

To learn more about Enterprise Library, see the Community Web site on CodePlex, and the Enterprise Library Home Page on MSDN.

patterns & practices Developer Center