While writing some sample applications for the upcoming release of Prism (Composite Application Guidance for WPF and Silverlight) I ran into a small challenge.
“How do you verify (with unit tests) that the right classes are registered in your DI-container?”
In my case, the container is Unity, but Unity does not have any ‘IsTypeRegistered’ methods (Apparently there are good reasons for it not to have these methods). So that posses an interesting challenge. At first I thought of 2 solutions:
But neither of these options were really satisfying. Then I asked Chris Tavarez, and he mentioned: Why don’t you build a Unity Extension. So I did and that solved the problem quite nicely:
So this is the Extension I’ve created:
1: public class QueryableContainerExtension : UnityContainerExtension
2: {
3: public List<RegisterEventArgs> Registrations = new List<RegisterEventArgs>();
4:
5: protected override void Initialize()
6: {
7: this.Context.Registering += new EventHandler<RegisterEventArgs>(Context_Registering);
8: }
9:
10: void Context_Registering(object sender, RegisterEventArgs e)
11: {
12: this.Registrations.Add(e);
13: }
14:
15: public bool IsTypeRegistered<TFrom, TTo>()
16: {
17: return this.Registrations.FirstOrDefault((e) => e.TypeFrom == typeof(TFrom) && e.TypeTo == typeof(TTo)) != null;
18: }
19:
20: public bool IsTypeRegisteredAsSingleton<TFrom, TTo>()
21: {
22: return this.Registrations.FirstOrDefault(
23: (e) => e.TypeFrom == typeof(TFrom)
24: && e.TypeTo == typeof(TTo)
25: && typeof(ContainerControlledLifetimeManager).IsInstanceOfType(e.LifetimeManager)) != null;
26: }
27: }
And this is how you’d use it:
1: [TestMethod]
2: public void TestRegistration()
3: {
4: // Create the container and add the extension method
5: var container = new UnityContainer();
6: var registeredTypes = new QueryableContainerExtension();
7: container.AddExtension(registeredTypes);
8:
9: // Register the classes to the container
10: container.Register<IMyInterface, MyClass>();
11:
12: // See if the type is registered
13: Assert.IsTrue(registeredTypes.IsTypeRegistered<IMyInterface, MyClass>());
14: }
Hope you find this as useful as I did :)