structuremap/structuremap — pull request #259 by BeeWarloc (2014-05-12 10:16:34+00:00)
Title: Fix race condition in PluginGraph

We've recentely gotten some strange NullReferenceException from StructureMap 2.6.4, now and then:

System.NullReferenceException: Object reference not set to an instance of an object.
at StructureMap.Graph.AssemblyScanner.ScanForAll(PluginGraph pluginGraph)
at StructureMap.Graph.PluginGraph.Seal()
at StructureMap.PluginGraphBuilder.Build()
..(etc)

We have not been able to reproduce this error in our development, but after carefully going through the ScanForAll method of AssemblyScanner we suspect that the problem is in a race condition in the WeakReference class.

The problem is that _reference.IsAlive is checked, and then _reference.Target is returned. This is a classic case of race condition where garbage collection could occur in the meantime.

Why this occurs several times each day I don't know, but I have a theory that checking IsActive actually could trigger a context switch and garbage collection.