You can retrieve a list of registrations from a container, and check if a specific registration is in the container.
This topic contains the following sections:
Viewing the Container Registrations and Mappings
The Unity container exposes the Registrations property which returns an IEnumerable list of the registrations within that container. Each registration is an instance of the ContainerRegistration class, which exposes information such as the registered type, the registration name (if any), the mapped type (if any), and the lifetime manager that the registration uses.
The following example uses this feature to display the contents of a container. It queries the Count() extension method for IEnumerable<T>, and then iterates through it displaying a list of the registrations and mappings.
C# |
Copy Code
|
void DisplayContainerRegistrations(IUnityContainer theContainer)
{
string regName, regType, mapTo, lifetime;
Console.WriteLine("Container has {0} Registrations:",
theContainer.Registrations.Count());
foreach (ContainerRegistration item in theContainer.Registrations)
{
regType = item.RegisteredType.Name;
mapTo = item.MappedToType.Name;
regName = item.Name ?? "[default]";
lifetime = item.LifetimeManagerType.Name;
if (mapTo != regType)
{
mapTo = " -> " + mapTo;
}
else
{
mapTo = string.Empty;
}
lifetime = lifetime.Substring(0, lifetime.Length - "LifetimeManager".Length);
Console.WriteLine("+ {0}{1} '{2}' {3}", regType, mapTo, regName, lifetime);
}
} |
Visual Basic |
Copy Code
|
Sub DisplayContainerRegistrations(ByVal theContainer As IUnityContainer)
Dim regName As String, regType As String, _
mapTo As String, lifetime As String
Console.WriteLine("Container has {0} Registrations:", _
theContainer.Registrations.Count())
For Each item As ContainerRegistration In theContainer.Registrations
regType = item.RegisteredType.Name
mapTo = item.MappedToType.Name
regName = If(item.Name, "[default]")
lifetime = item.LifetimeManagerType.Name
If mapTo <> regType Then
mapTo = " -> " & mapTo
Else
mapTo = String.Empty
End If
lifetime = lifetime.Substring( _
0, lifetime.Length - "LifetimeManager".Length)
Console.WriteLine("+ {0}{1} '{2}' {3}", _
regType, mapTo, regName, lifetime)
Next
End Sub |
The Name property of a ContainerRegistration instance returns null (C#) or Nothing (Visual Basic) for default (unnamed) registrations. The MappedToType property has the same value as the RegisteredType when this is a non-mapped concrete type registration (rather than a base class or interface mapped to a concrete type).
Checking for the Existence of a Specific Registration