views:

265

answers:

1

Possibly a stupid question, but during debug I simply want to see the types that have been registered with my Unity container. I have tried going through the container in the watch window, but can't seem to find what I am looking for? I am expecting there to be a list of registered types somewhere?

Thanks in advance

+2  A: 

I think it is in there but it's pretty buried. Usually I use the following extension:

using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Practices.Unity;

namespace NBody.Viewer.Unity

{
    public class QueryableContainerExtension : UnityContainerExtension
    {
        private List<RegisterEventArgs> _registrations;
        public IList<RegisterEventArgs> Registrations
        {
            get { return new ReadOnlyCollection<RegisterEventArgs>(_registrations); }
        }

        private List<RegisterInstanceEventArgs> _instanceRegistrations;
        public IList<RegisterInstanceEventArgs> InstanceRegistrations
        {
            get { return new ReadOnlyCollection<RegisterInstanceEventArgs>(_instanceRegistrations); }
        }

        protected override void Initialize()
        {
            _registrations = new List<RegisterEventArgs>();
            _instanceRegistrations = new List<RegisterInstanceEventArgs>();
            Context.Registering += (s, e) => _registrations.Add(e);
            Context.RegisteringInstance += (s, e) => _instanceRegistrations.Add(e);
        }

        public bool IsTypeRegistered<TFrom, TTo>()
        {
            return _registrations.Exists(e => e.TypeFrom == typeof(TFrom) && e.TypeTo == typeof(TTo));
        }

        public bool IsTypeRegistered<TFrom>()
        {
            return _registrations.Exists(e => e.TypeFrom == typeof(TFrom));
        }
    }
}

Then you can write code like this:

    [Fact]
    public void IsTypeRegisteredReturnsTrueForRegisteredType()
    {
        QueryableContainerExtension target = new QueryableContainerExtension();
        IUnityContainer container = new UnityContainer();
        container.AddExtension(target);

        container.RegisterType<IEnumerable, Array>();

        Assert.True(target.IsTypeRegistered<IEnumerable, Array>());
        Assert.True(target.IsTypeRegistered<IEnumerable>());
        Assert.False(target.IsTypeRegistered<IEnumerable, SortedList>());
        Assert.False(target.IsTypeRegistered<IList>());
    }

You could use this approach or you could wrap or alter the source for the container to add a DebuggerDisplay attribute and a method which uses the above code to iterate through the container contents.

Hope this helps!

Ade Miller
Unity 2.0 supports a container Registrations enumeration and IsRegistered method which makes the above code obsolete.
Ade Miller