Share via


Unity Application Block Methods

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 following tables list the methods of the UnityContainer class provided by in the Unity Application Block. The method overloads are grouped into the following categories:

  • Constructing and disposing instances of the UnityContainer class
  • Registering type mappings with the container
  • Registering existing object instances with the container
  • Resolving references to objects
  • Resolving references to all named objects of a specified type
  • Building up existing object instances
  • Managing container extensions
  • Using the UnityContainer Fluent Interface

Note

The provision of both generic and non-generic overloads of many of the Unity container methods ensures that the Unity Application Block can be used in languages that do not support generics. You can use either approach (the generic or the non-generic overloads) in your code and mix them as required. For example, you can register mappings using the generic overloads and then retrieve object instances using the non-generic overloads, and vice versa.

There are limitations when using Unity in a partial trust environment. For more details, see Using Unity in Partial Trust Environments.

Constructing and Disposing Instances of the UnityContainer Class

These methods allow you to create a new default UnityContainer, create a child container that has a specified UnityContainer as its parent, and dispose an existing container.

Method

Description

UnityContainer( )

Creates a default UnityContainer. Returns a reference to the new container.

CreateChildContainer( )

Creates a new nested UnityContainer as a child of the current container. The current container will apply its own settings first, and then check the parent for additional settings. Returns a reference to the new container.

Dispose( )

Disposes this container instance and any child containers. Also disposes any registered object instances whose lifetimes are managed by the container.

Registering Type Mappings with the Container

The RegisterType method registers a type with the container. At the appropriate time, the container will build an instance of the type you specify. This could be in response to dependency injection initiated through class attributes or when you call the Resolve method. The lifetime of the object it builds will correspond to the lifetime you specify in the parameters of the method. If you do not specify a value for the lifetime, the type is registered for a transient lifetime—the container will create a new instance on each call to Resolve.

This method is useful for retrieving instances of different objects that implement the same specified interface or that inherit from the same specified base class. The target type for the mapping (the TTo or to parameter in the following table) must inherit from or implement the base type or interface of the source (the TFrom or from parameter in the following table). The LifetimeManager passed to some of the methods controls when object instances are created and disposed. Unity contains default LifetimeManager types for singleton and instance registration. All of these methods return a reference to the UnityContainer upon which the method was called, equivalent to this in C# or Me in Visual Basic.

Method

Description

RegisterType<TFrom, TTo>( )

Registers a default type mapping with the container so that it will return an instance of the type specified as TTo when a Resolve method requests an instance of the type TFrom.

RegisterType<TFrom, TTo>(LifetimeManager lifetime)

Registers a default type mapping with the container so that it will return an instance of the type specified as TTo when a Resolve method requests an instance of the type TFrom. Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

RegisterType<TFrom, TTo>(String name)

Registers a named type mapping with the container so that it will return an instance of the type specified as TTo when a Resolve method requests an instance of the type TFrom with the specified name. If name is null, generates a default type mapping. Names are case-sensitive.

RegisterType<TFrom, TTo>(String name, LifetimeManager lifetime)

Registers a named type mapping with the container so that it will return an instance of the type specified as TTo when a Resolve method requests an instance of the type TFrom with the specified name. If name is null, generates a default type mapping. Names are case-sensitive. Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

RegisterType<T>(LifetimeManager lifetime)

Creates a default type registration with the container so that it will return an instance of that type in response to a call from the Resolve method. Allows you to register a LifetimeManager with the container to manage the lifetime of the registered type.

RegisterType<T>(String name, LifetimeManager lifetime)

Creates a named type registration with the container so that it will return an instance of that type in response to a call from the Resolve method with the specified name. Allows you to register a LifetimeManager with the container to manage the lifetime of the registered type.

RegisterType(Type from, Type to)

Registers a default type mapping with the container so that it will return an instance of the type specified as to when a Resolve method requests an instance of the type from.

RegisterType(Type from, Type to, String name)

Registers a named type mapping with the container so that it will return an instance of the type specified as to when a Resolve method requests an instance of the type from with the specified name. If name is null, generates a default type mapping. Names are case-sensitive.

RegisterType(Type from, Type to, LifetimeManager lifetime)

Registers a default type mapping with the container so that it will return an instance of the type specified as to when a Resolve method requests an instance of the type from. Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

RegisterType(Type from, Type to, String name, LifetimeManager lifetime)

Registers a named type mapping with the container so that it will return an instance of the type specified as to when a Resolve method requests an instance of the type from with the specified name. If name is null, generates a default type mapping. Names are case-sensitive. Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

RegisterType(Type t, LifetimeManager lifetime)

Creates a default type registration with the container so that it will return an instance of that type in response to a call from the Resolve method. Allows you to register a LifetimeManager with the container to manage the lifetime of the registered type.

RegisterType(Type t, String name, LifetimeManager lifetime)

Creates a named type registration with the container so that it will return an instance of that type in response to a call from the Resolve method with the specified name. Allows you to register a LifetimeManager with the container to manage the lifetime of the registered type.

You can use the RegisterType method to register open generic types. The following code registers a type mapping between an example interface named IRepository and a concrete type named SqlRepository that implements this interface. The code then registers a mapping for the SqlRepository type as an open generic type, and shows how you can resolve a specific instance using the IRepository interface as the dependency identifier.

public interface IRepository<TEntity> 
{
  TEntity GetById(int id);
}

public class SqlRepository<TEntity> : IRepository
{
  public TEntity GetById(int id) 
  {
    ... 
  }
}

IUnityContainer myContainer = new UnityContainer();
myContainer.RegisterType(typeof(IRepository<>), typeof(SqlRepository<>));
IRepository<Customer> result = myContainer.Resolve<IRepository<Customer>>();
'Usage
Public Interface IRepository(Of TEntity)
  Function GetById(ByVal id As Integer) As TEntity
End Interface

Public Class SqlRepository(Of TEntity)
  Implements IRepository(Of TEntity)
  Public Function GetById(ByVal id As Integer) As TEntity _
                  Implements IRepository(Of TEntity).GetById
    ... 
  End Function
End Class

Dim myContainer As IUnityContainer = New UnityContainer()
myContainer.RegisterType(GetType(IRepository(Of )), GetType(SqlRepository(Of )))
Dim result As IRepository(Of Customer) = myContainer.Resolve(Of IRepository(Of Customer)())()

Registering Existing Object Instances with the Container

The RegisterInstance method registers with the container an existing instance of a type that you specify, with the lifetime that you specify. The container will return the exiting instance during that lifetime. If you do not specify a value for the lifetime, the instance will have the default container-controlled lifetime.

Instance registration is similar to type registration, except that you first create the instance directly and then use the RegisterInstance method to add that instance to the container. Therefore, the container does not need to create the instance on the first Resolve request. These methods are useful if you already have an instance of an object you have previously configured. The LifetimeManager passed to some of the methods controls when object instances are created and disposed. Unity contains default LifetimeManager types for singleton and instance registration. The methods return a reference to the UnityContainer upon which the method was called, equivalent to this in C# or Me in Visual Basic.

Method

Description

RegisterInstance<TInterface>(TInterface instance)

Registers a default instance mapping with the container so that it will return the specified instance when a Resolve method requests an instance of the type TInterface (which can be an implemented interface instead of the actual type). The container takes over the lifetime of the instance.

RegisterInstance<TInterface>(TInterface instance, LifetimeManager lifetime)

Registers a default instance mapping with the container so that it will return the specified instance when a Resolve method requests an instance of the type TInterface (which can be an implemented interface instead of the actual type). Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

RegisterInstance<TInterface>(String name, TInterface instance)

Registers a named instance mapping with the container so that it will return the specified instance when a Resolve method requests an instance of the type TInterface (which can be an implemented interface instead of the actual type) and the specified name. The container takes over the lifetime of the instance. Names are case-sensitive.

RegisterInstance<TInterface>(String name, TInterface instance, LifetimeManager lifetime)

Registers a named instance mapping with the container so that it will return the specified instance when a Resolve method requests an instance of the type TInterface (which can be an implemented interface instead of the actual type) and the specified name. Names are case-sensitive. Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

RegisterInstance(Type t, Object instance)

Registers a default instance mapping with the container so that it will return the specified instance when a Resolve method requests an instance of the type t (which can be an implemented interface instead of the actual type). The container takes over the lifetime of the instance.

RegisterInstance(Type t, Object instance, LifetimeManager lifetime)

Registers a default instance mapping with the container so that it will return the specified instance when a Resolve method requests an instance of the type t (which can be an implemented interface instead of the actual type). Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

RegisterInstance(Type t, String name, Object instance)

Registers a named instance mapping with the container so that it will return the specified instance when a Resolve method requests an instance of the type t (which can be an implemented interface instead of the actual type) and the specified name. Names are case-sensitive. Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

RegisterInstance(Type t, String name, Object instance, LifetimeManager lifetime)

Registers a named instance mapping with the container so that it will return the specified instance when a Resolve method requests an instance of the type t (which can be an implemented interface instead of the actual type) and the specified name. Names are case-sensitive. Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

You can use the RegisterInstance method to register open generic types with non-ambiguous constructors. For example, you can register an existing instance of the Dictionary type. The following code creates and populates a Dictionary, then registers it using the RegisterInstance method.

IUnityContainer myContainer = new UnityContainer();
Dictionary<string, string> myDict = new Dictionary<string, string>();
myDict.Add("One", "ABC");
myDict.Add("Two", "DEF");
myContainer.RegisterInstance(myDict);
'Usage
Dim myContainer As IUnityContainer = New UnityContainer()
Dim myDict As New Dictionary(Of String, String)()
myDict.Add("One", "ABC")
myDict.Add("Two", "DEF")
myContainer.RegisterInstance(myDict)

Resolving References to Objects

These methods return instances of objects based on the mappings registered with the container. You can request objects using just the type, or the type and the registered name.

Method

Description

Resolve<T>( )

Returns an instance of the default type registered with the container as the type T.

Resolve<T>(string name)

Returns an instance of the type registered with the container as the type T with the specified name. Names are case-sensitive.

Resolve(Type t)

Returns an instance of the default type registered with the container as the type t.

Resolve(Type t, string name)

Returns an instance of the default type registered with the container as the type t with the specified name. Names are case-sensitive.

Resolving References to All Named Objects of a Specified Type

These methods return an enumerable list of instances of objects based on the named (non-default) mappings registered with the container. You can only request a list of objects using the object type. These methods are useful if you have registered multiple object or interface types using the same type but different names.

Method

Description

ResolveAll<T>( )

Returns a list of IEnumerable<T> where T is the type registered as a non-default mapping with the container as the type T.

ResolveAll(Type t)

Returns a list of IEnumerable<object> where object is the type registered as a non-default mapping with the container as the type t.

Note

The ResolveAll method overloads only return types that you registered with a specified name. They do not return instances for any default (un-named) registration mappings.

Building Up Existing Object Instances

These methods pass an existing object through the container and perform injection upon it. These methods are useful when you do not have control of the construction of an instance (for example, in ASP.NET pages or for objects created through XAML), but you still want property or method call injection performed. The methods return the resulting object, although container extensions may add other features that cause the methods to return a different object that is type-compatible with the existing object. For example, a strategy in ObjectBuilder may create and return a proxy for an object instead of the actual object.

Method

Description

BuildUp<T>(T existing)

Passes the existing object of type T through the container and performs all configured injection upon it.

BuildUp<T>(T existing, string name)

Passes the existing object of type T with the specified name through the container and performs all configured injection upon it.

BuildUp(Type t, object existing)

Passes the existing object of type t through the container and performs all configured injection upon it.

BuildUp(Type t, object existing, string name)

Passes the existing object of type t with the specified name through the container and performs all configured injection upon it.

Note

The UnityContainer class also exposes the Teardown method, which notionally would reverse the build-up process. However, the base implementation of this method does nothing. The implementation exists so that container extensions can execute their own custom overrides of this method if required.

Managing Container Extensions

These methods allow you to add custom extensions to a container and remove all extensions. You can also access the configuration information exposed by an extension. For more information about building and working with container extensions, see Extending and Modifying the Unity Application Block.

Method

Description

AddExtension(UnityContainerExtension extension)

Adds the specified extension object, which must be of type UnityContainerExtension, to the container. Returns a reference to the container, equivalent to this in C# or Me in Visual Basic.

AddNewExtension<TExtension>( )

Creates a new extension object of type TExtension and adds it to the container. The extension type must have a zero-argument public constructor. Returns a reference to the container, equivalent to this in C# or Me in Visual Basic.

Configure<TConfigurator>( )

Returns the configuration of the specified extension interface as an object of type TConfigurator, or null if the specified extension interface is not found. Extensions can expose configuration interfaces as well as adding strategies and policies to the container. This method walks the list of extensions and returns the first one that implements the specified type.

Configure(Type configurationInterface)

Returns the configuration of the specified extension interface as an object of type configurationInterface, or null if the specified extension interface is not found. Extensions can expose configuration interfaces as well as adding strategies and policies to the container. This method walks the list of extensions and returns the first one that implements the specified type.

RemoveAllExtensions( )

Removes all installed extensions from the container, including all extensions that implement the default behavior, but it does not remove registered instances and singletons already set up in the container. To use the container again, after executing this method, you must add either the default extensions or your own custom extensions. Returns a reference to the container, equivalent to this in C# or Me in Visual Basic.

Using the UnityContainer Fluent Interface

The API for the Unity container also provides a fluent interface. This means that you can chain method calls in one statement. To use the fluent interface, call all the methods you want one after the other in a single statement, as shown in this code.

IUnityContainer myContainer = new UnityContainer()
   .RegisterType<IMyService, DataService>()
   .RegisterType<IMyService, EmailService>()
   .RegisterType<MyServiceBase, LoggingService>();
'Usage
Dim myContainer As IUnityContainer = New UnityContainer() _
   .RegisterType(Of IMyService, DataService)() _
   .RegisterType(Of IMyService, EmailService)() _
   .RegisterType(Of MyServiceBase, LoggingService)() 

You can use this approach to chain any of the methods of the UnityContainer class when you create the container. For example, you can use any combination of the RegisterType, RegisterInstance, AddExtension, and Configure methods to prepare the container.

Note

When using Visual Basic, you should use the full syntax for declaring the container as shown in the previous code example. If you use the short syntax Dim myContainer As New UnityContainer(), the fluent interface mechanism will not allow IntelliSense to display the members of the container, and you may see syntax checking errors in the code.