Saturday, January 14, 2012

NullReferenceException in StructureMap after refactoring

I've encountered strange NullReferenceException in StructureMap when defining constructor arguments for the dependency after major refactoring and making previously abstract class non-abstract. Here is the code I had:

public interface IClass {}

public /*abstract*/ class Class : IClass
{
protected Class(string test) {}
}

public class TheRegistry : Registry
{
public TheRegistry()
{
For<IClass>().Use<Class>()
.Ctor<string>().Is("test");
}
}

And here's the stack trace of inner NullReferenceException:

   at StructureMap.Graph.Constructor.FindFirstConstructorArgumentOfType(Type type)
in c:\code\structuremap\Source\StructureMap\Graph\Constructor.cs:line 82
at StructureMap.Graph.Plugin.FindArgumentNameForType(Type type, CannotFindProperty cannotFind)
in c:\code\structuremap\Source\StructureMap\Graph\Plugin.cs:line 92
at StructureMap.Graph.Plugin.FindArgumentNameForType[T]()
in c:\code\structuremap\Source\StructureMap\Graph\Plugin.cs:line 77
at StructureMap.Pipeline.SmartInstance`1.getArgumentNameForType[CTORTYPE]()
in c:\code\structuremap\Source\StructureMap\Pipeline\SmartInstance.cs:line 226
at StructureMap.Pipeline.SmartInstance`1.Ctor[CTORTYPE]()
in c:\code\structuremap\Source\StructureMap\Pipeline\SmartInstance.cs:line 219
at NHManyToMany.TheRegistry..ctor()
in C:\Documents and Settings\Adam\Moje dokumenty\Projects\test\NHManyToMany\TheRegistry.cs:line 21

StructureMap can't find string-typed argument in the constructor. Most probably the exception like this will be thrown where there's no constructor with string argument. But in my case, there was one.

It took me some time to figure out what's wrong here - my constructor is protected, thus inaccessible for StructureMap. I forgot to change it into public after removing the abstract keyword. StructureMap obviously need to have an accessible constructor to work with, so the same issue may come out with internal constructors from other assemblies.

No comments:

Post a Comment