Partager 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 Unity Application Block information can be found at the Unity Application Block 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 information, 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 first applies its own settings, and then it checks 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 builds 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 corresponds 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 creates 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>(params InjectionMember[] injectionMembers)

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

RegisterType<TFrom, TTo>(LifetimeManager lifetime,params InjectionMember[] injectionMembers)

Registers a default type mapping with the container so that it returns 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,params InjectionMember[] injectionMembers)

Registers a named type mapping with the container so that it returns 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,params InjectionMember[] injectionMembers)

Registers a named type mapping with the container so that it returns 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,params InjectionMember[] injectionMembers)

Creates a default type registration with the container so that it returns 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,params InjectionMember[] injectionMembers)

Creates a named type registration with the container so that it returns 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,params InjectionMember[] injectionMembers)

Registers a default type mapping with the container so that it returns 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,params InjectionMember[] injectionMembers)

Registers a named type mapping with the container so that it returns 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,params InjectionMember[] injectionMembers)

Registers a default type mapping with the container so that it returns 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,params InjectionMember[] injectionMembers)

Registers a named type mapping with the container so that it returns 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,params InjectionMember[] injectionMembers)

Creates a default type registration with the container so that it returns 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,params InjectionMember[] injectionMembers)

Creates a named type registration with the container so that it returns 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 returns the existing instance during that lifetime. If you do not specify a value for the lifetime, the instance has 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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 returns 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, and it then registers the Dictionary 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 only 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 theoretically 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 are methods you can use 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 in addition to 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 in addition to 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 the following 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 does not allow IntelliSense to display the members of the container, and you may see syntax checking errors in the code.