Type Tracking Extension for Unity

Edit: Source code posted to [Hazware Unity Extensions on GitHub]

My personal inversion of control container is Unity. However, I occasionally find myself looking for functionality from the other .NET IoC containers I have used, such as Ninject and Castle Windsor. Here is the code that came out from trying to solve this need.

I was working on some Unit of Work code for NHibernate and I found the need to query the container to check if a type was registered. I checked the Unity documentation for the

method, and as usual, the documentation always seems to be missing the piece of information I need. It did not describe the result of calling the container for a type that is not registered. Having used Unity for a while now, I was pretty sure it through an exception, but just be sure, I wrote a quick test.

public void TestUnity()

And result:

Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "System.IDisposable", name ="". Exception message is: The current build operation (build key Build Key[System.IDisposable, null]) failed: The current type, System.IDisposable, is an interface and cannot be constructed. Are you missing a type mapping?

I could not find another way to check for type registration, so off to Google I went. One discussion from the Unity discussion group seemed to cover this program [see: IsInstanceRegistered?]. This seemed to be the answer, until I compared against my unit tests to validate my usage. The solution provided does not provide for checked for default or named registered types. The problem is that Unity has a keyed resolver in that it either returns a default registration that is unnamed, or a specifically named registration. Thus, it is possible for this check to return true, but for the Resolve call to fail. I wanted something more in line with Unity’s usage model.

I did find one other posted solution. That solution recommend just doing a ResolveAll and returning true if the collection was not empty. However, this is highly inefficient. It forces resolution of the types, triggering instantiation, even if not needed.

Given these limitations, I decided to write my own solution. I like the idea of doing it as a Unity extension, so I retained that model. So here is my code for solution.

{% gist dbuksbaum/9d635366d98df0221c99 %}


comments powered by Disqus