Resolving Objects

Microsoft Enterprise Library 5.0

DropDown image DropDownHover image Collapse image Expand image CollapseAll image ExpandAll image Copy image CopyHover image

You can use the Unity container to generate instances of any object that has a public constructor (in other words, objects that you can create using the new operator), without registering a mapping for that type with the container. When you call the Resolve method and specify the default instance of a type that is not registered, the container simply generates and returns an instance of that type. However, the only time that this is realistically practical is when the object you are generating contains dependency attributes that the container will use to inject dependent objects into the requested object.

The Unity container identifies type registrations and type mappings in the container using a type and, optionally, a name. The type is an interface or a class (usually an interface or base class) that the desired concrete object type implements or inherits. This identifies the mapping so that the container can retrieve the correct object type in response to a call to the Resolve or ResolveAll method. Where there is more than one mapping for the same type, the optional name differentiates these mappings and allows code to specify which of the mappings for that type to use.

The provision of both generic and non-generic overloads of many of the Unity container methods ensures that Unity 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.

When you attempt to resolve an abstract base class or interface where there is no matching type mapping in the container, Unity will attempt to create a new instance of the class you specified. As it cannot construct and populate an instance of an abstract class or an interface, Unity will raise an exception.

When you attempt to resolve a non-mapped concrete class that does not have a matching registration in the container, Unity will create an instance of that class and populate any dependencies.

The following topics describe how you can resolve objects using the Resolve or ResolveAll methods:

For more information about how you can configure Unity with type registrations and mappings, see Configuring Unity.

For more information about how you can perform dependency injection on existing object instances, see Using BuildUp to Wire Up Objects Not Created by the Container.