Posts

Decorating Unity extension

First I want to give credit where it is due, the code in this post is based largely on the code I found in this post by Jim Chrisopher. The original code required me to register my decorators before registering the type I wanted to decorate.  I didn't like this because I prefer to register all the low-level services from within their own assemblies and then have the app (website etc) decorate those types at a higher level.  So I changed the code in the following ways It now uses the UnityContainer.Configure<> method to decorate types. The decorators may be registered before or after the registered type, or both, it doesn't matter. It is possible to register both generic and non-generic types, and both will be used if applicable (e.g. ICommand<> and ICommand<string> would apply to Command<string> but only ICommand<> would apply to Command<int>.) It works with child containers. It uses the context.NewBuild method instead of requiring an

SpinLock SynchronizationLockException - The calling thread does not hold the lock

Here is the code from a console app. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication48 { class Program { static readonly SpinLock SpinLock = new SpinLock(); static void Main( string [] args) { bool lockTaken = false ; try { SpinLock.Enter( ref lockTaken); if (lockTaken) Console.WriteLine( " Lock taken " ); } finally { if (lockTaken) SpinLock.Exit(); } Console.WriteLine( " Done " ); } } } So why would this single-threaded app tell me that the thread trying to call SpinLock.Exit() doesn’t hold the lock? SpinLock is a value type.  When you mark a field referencing a reference type as readonly you are not only making the field unassigna