Export (0) Print
Expand All

Retrieving Container Registration Information

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:

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.

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);
    }
}

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).

You can also use the methods of the container to check if a specific registration or mapping exists. The IsRegistered method takes a container, a type, and optionally a registration name, and returns True or False. For example, to check if there is a registration in the container for the type MyEmailService, you would use the following code.

IUnityContainer container = new UnityContainer();
bool result = container.IsRegistered<MyEmailService>();

This will return True if there is a default (unnamed) registration for the MyEmailService type. If you want to check for the presence of a named registration, you simply specify the name in the call to the IsRegistered method, as shown in the following example.

bool result = IsRegistered<MyEmailService>("EMailHandler");

Show:
© 2014 Microsoft