Creating Objects Using the Unity Application Block

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

The Unity Application Block provides new opportunities for developers in the way that they write their business objects and services, and how they organize and architect their applications. It also provides new opportunities for developers when they write code to interact with Enterprise Library. In this version of Enterprise Library, you can create instances of Enterprise Library objects and your own custom business object using the dependency injection container provided by the Unity Application Block.

This new feature does not affect existing code, and a great deal of work has gone into making sure that this version of Enterprise Library is compatible with existing code and applications. However, the Unity integration feature is the recommended approach for new application development, though developers can choose which technique they prefer.

In the following sections of this topic, you will see how to create instances of application block objects:

  • About the Unity Application Block
  • Creating Enterprise Library Objects with the Unity Application Block
  • Injecting Enterprise Library Objects into Custom Business Objects

Note

For information about how you can use the Unity Application Block to create instances of your own objects and services and how to use it as a stand-alone dependency injection mechanism, see The Unity Application Block. For information about the design of the Enterprise Library integration with Unity, and how you can extend this integration, see The Injection Model.

About the Unity Application Block

The Unity Application Block implements a dependency injection container named UnityContainer and exposes methods to register mappings between interfaces or classes (typically base classes or abstract classes) and concrete types (both instance and singleton types), get instances of objects, and build up existing objects with dependent object instances. The instances returned from the Resolve and BuildUp methods contain the appropriate dependent object instances based on the registration of types within the container. You can also create a nested container hierarchy, and manage the lifetime of each object and container.

The Unity Application Block does not automatically read its configuration information or create and prepare containers. To provide maximum flexibility, you use code in your application to instantiate a Unity container and then populate it with the registrations, type mappings, and extensions. These can be defined in a configuration file that you load into a container, or you can populate and modify the configuration of a container directly using the methods of the container.

You can include the configuration information for Unity in the App.config or Web.config file that contains your Enterprise Library configuration information, or you can use a separate configuration file or configuration source for Unity.

However, in this release of Enterprise Library, if you include the Unity configuration in your Enterprise Library configuration file, you must manually edit the sections for the Unity Application Block using a text editor or the built-in Visual Studio text editor. For information about configuring the Unity Application Block and the code you use to create containers and load configuration information, see Entering Configuration Information in the Unity Application Block documentation.

The following table describes the Unity container methods that return object instances and are suitable for use with Enterprise Library objects.

Method signature

Description

Resolve<T>()

Returns a concrete instance of the type that is registered for the generic type T and is the default object of this type in the configuration.

Resolve<T>(string name)

Returns a concrete instance of the type that is registered for the generic type T and has the specified name.

Resolve(Type t)

Returns as an Object type a concrete instance of the type that is registered for the type t and is the default object of this type in the configuration.

Resolve(Type t, string name)

Returns as an Object type a concrete instance of the type that is registered for the type t and has the specified name.

Creating Enterprise Library Objects with the Unity Application Block

This section shows how you can use the methods listed in the previous table to get instances of Enterprise Library application block objects. The first stage is to create a Unity container and add the Enterprise Library core configuration extension to it, as shown in the following code.

IUnityContainer uContainer = new UnityContainer();
uContainer.AddNewExtension<EnterpriseLibraryCoreExtension>();
'Usage
Dim uContainer As IUnityContainer = New UnityContainer()
uContainer.AddNewExtension(Of EnterpriseLibraryCoreExtension)()

By default, this extension will read its configuration from the application configuration file (App.config or Web.config). If you want to provide a custom configuration source, you create this first and pass it to the EnterpriseLibraryCoreExtension as shown in the following code.

IUnityContainer uContainer = new UnityContainer();
IConfigurationSource configSource = new MyCustomConfigSource();
// ... populate configuration source as required here
uContainer.AddExtension(new EnterpriseLibraryCoreExtension(configSource));
'Usage
Dim uContainer As IUnityContainer = New UnityContainer()
Dim configSource As IConfigurationSource = New MyCustomConfigSource()
' ... populate configuration source as required here
uContainer.AddExtension(Of New EnterpriseLibraryCoreExtension(configSource))

Note

You must add the EnterpriseLibraryCoreExtension to the container before you add any other Enterprise Library extension (you can add other extensions that are not part of Enterprise Library at any stage). If you have an existing container that has Enterprise Library extensions, you can remove them using the RemoveAllExtensions method and then add them back in the correct order.

The next step is to add to the container the specific extension for the application block you want to use. You can load more than one application block extension if required. The name of the extension you add for each block is made up of the Application Block name followed by "BlockExtension" — such as DataAccessBlockExtension, LoggingBlockExtension, and ExceptionHandlingBlockExtension. The following code shows how to load the configuration extension for the Caching Application Block.

uContainer.AddNewExtension<CachingBlockExtension>();
'Usage
uContainer.AddNewExtension(Of CachingBlockExtension)()

Note

When you use an application block that has a dependency on other application blocks, you must add the appropriate application block extensions as well as the extension for the application block you actually want to use. For example, to use the Caching Application Block to store cached data in a database, you must add both the CachingBlockExtension and the DataAccessBlockExtension; and, if you want to encrypt cached data, you must also add the CryptographyBlockExtension. The application block extensions available in this release of Enterprise Library are DataAccessBlockExtension, CachingBlockExtension, SecurityBlockExtension, CryptographyBlockExtension, ExceptionHandlingBlockExtension, LoggingBlockExtension and Policy Injection Application Block.

You can now retrieve instances of providers or other objects defined in the standard configuration of Enterprise Library using the Resolve method of the container. For 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 configuration
ICacheManager cacheMgr = uContainer.Resolve<ICacheManager>();

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

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

Note

The Enterprise Library configuration generated by the container extensions will be lost when the container is disposed. Therefore, to use the application block objects, you must keep a strong reference to the container in your code. In addition, the objects you create using the application block extensions and the Resolve method of the container are singleton instances whose lifetime is controlled by the Unity container. They will be disposed when the container is disposed or goes out of scope.

Specifying Unity Integration through Configuration

An alternative approach is to specify the configuration requirements in your configuration source. You can configure either or both of the following:

  • You can specify the block extensions you want to use in the Unity configuration.
  • You can specify how Unity should build Enterprise Library objects using the type configuration element in the Unity configuration to define mappings between types (for example, a mapping that returns a SqlDatabase instance when you call the Resolve method or specify injection of the Database type). You can also specify the lifetime and other construction policies of objects using this approach.

The Enterprise Library configuration schema and the Unity Application Block schema are independent. However, you can include a configuration section for the Unity Application Block (where you can specify the configuration for one or more Unity containers; and the types, mappings, instances, and extensions for each container) in the same file as the Enterprise Library configuration. For information on the Unity configuration schema and examples of its use, see Entering Configuration Information in the documentation for The Unity Application Block.

Using the Enterprise Library Integration Facades

You can use Unity to inject instances of Enterprise Library objects into your custom objects and classes. For more information, see the following section Injecting Enterprise Library Objects into Custom Business Objects.

However, some features of Enterprise Library are provided by static façades that cannot be injected. Instead, you can use the new non-static façades provided with the application blocks. The following table shows the façades you can use and the corresponding static Enterprise Library façade that they replace.

Existing façade

New façade for use with Unity

ExceptionPolicy

ExceptionManager

Tracer

TraceManager

Cryptographer

CryptographyManager

Injecting Enterprise Library Objects into Custom Business Objects

You can also use the Unity Application Block to inject instances of the Enterprise Library objects and services into custom business objects and components. This example shows how a custom class can depend on a LogWriter instance. The following code shows the custom class.

public class MyNewObject
{
  public MyNewObject(LogWriter myLogger)
  { 
    myLogger.Write("Some message");
  }
} 
'Usage
Public Class MyNewObject
  Public Sub New(myLogger As LogWriter)
    myLogger.Write("Some message")
  End Sub
End Class 

You can then load the Enterprise Library core extension and the Logging Application Block extension into a Unity container, and then you can instantiate the custom class complete with the injected reference to the LogWriter class, as shown in the following code.

IUnityContainer uContainer = new UnityContainer();
uContainer.AddNewExtension<EnterpriseLibraryCoreExtension>();
uContainer.AddNewExtension<LoggingBlockExtension>();
MyNewObject myNewInstance = uContainer.Resolve<MyNewObject>();
'Usage
Dim uContainer As IUnityContainer = New UnityContainer()
uContainer.AddNewExtension(Of EnterpriseLibraryCoreExtension)()
uContainer.AddNewExtension(Of LoggingBlockExtension)()
Dim myNewInstance As MyNewObject = uContainer.Resolve(Of MyNewObject)()

Note

To use this approach to creating instances of application block objects, you must add the Unity Application Block to your application configuration using the Enterprise Library configuration tools. For information about how to add application blocks to your Enterprise Library configuration, see Configuring Enterprise Library. For details of how to configure the Unity Application Block, see Entering Configuration Information in the Unity Application Block documentation. For information about using the dependency injection features of the Unity Application Block, see The Unity Application Block.