A Thread-Safe Global Unity Container

by Larry Spencer Wednesday, January 4, 2012 8:10 AM

This is the post that would not die.

I wrote it earlier this year, and then decideded that a global Unity container was a bad idea (even if it was thread-safe). Much better is what Mark Seemann calls the Composition Root -- a place at the top of your application's call stack where all dependency injections are resolved once and for all. See Mark's post, Composition Root. I also recommend Mark's book, Dependency Injection in .NET, for more best-practice guidance.

Having seen the benefits of a Composition Root over the Service Locator anti-pattern that my global Unity container entailed, I deleted my original post.

Unfortunately, links to it live on in a few places and people have emailed me to ask for the code. They are stuck with a legacy app where it's too late or too much trouble to go with a Composition Root. Having been in that uncomfortable spot myself, I now re-offer the Thread-Safe Global Unity Container. I've manually pre-dated this post so those links will point to it.

My solution consists of two classes. UnitySingleton is the public wrapper for an internal class, UnitySingletonInternal. The outer class presents easy-to-use static methods and acquires the correct kind of lock (read or write) for whatever you're trying to do.

The first time you access the container, the code will load the type-registrations in your .config file. You can also register types programmatically with the static RegisterInstance method.

 

UnitySingleton.RegisterInstance<IMyType>(new MyConcreteType());

 

To resolve a type, use the static Resolve method:

 

var myObject = UnitySingleton.Resolve<IMyTypeType>();

 

Finally, the static FindRegistrationSingle method exposes an existing ContainerRegistration so you can tinker with it.

For additional details, please download the solution here ThreadSafeUnityContainer.zip (569.10 kb) and peruse the UnitySingleton class. 

Tags: , , ,

Dependency Injection

About the Author

Larry Spencer

Larry Spencer develops software with the Microsoft .NET Framework for ScerIS, a document-management company in Sudbury, MA.