Auto-generate NullObjects

NullObjects are a very usefull pattern. Among some other things they can be used as a means of defensive programming. If you have a dependency of a certain type (say ILogger) and don’t want make it an optional dependency using property injection (with the added downside of having to check for null every time you access that property) you can use a NullObject (in this case a NullLogger) to ensure that an instance of your interface is always present. Better prevent errors in the first place than telling people what they did wrong afterwards.

But do you really want to spend the time to implement classes that do … nothing?!

I consider DI containers (and infrastructure in general) a great tool to relieve programmers of the burden of routine tasks. Maybe that’s because I’m lazy and don’t want to do the same work twice.

A while ago Oren Eini announced a challenge for a Null Object Dependency Facility for Castle Windsor. I don’t know wether that challenge ever resulted in any actual code but I think its fun to solve that problem for Unity.

After some fiddling around with Reflection.Emit (again…) I am proud to announce that Unity can automatically generate and inject implementations even for trickier interfaces (like TryGetValue with out parameters). The generated code will never return null for strings or collections but empty strings and collections instead.

The functionality is accessible via an extension method for IUnityContainer.

public static IUnityContainer RegisterNullObject(this IUnityContainer container,
    Type contract, string name, LifetimeManager lifetime, 
    params InjectionMember[] injectionMembers)

Get the source code here (project TecX.Unity folder Proxies and the test suite that shows how to use it in TecX.Unity.Proxies.Test).