开发者

Unable to call BuildUp from a private or internal constructor with StructureMap

In one of my classes I have an internal constructor which is being used for unit testing, and a private constructor that my application calls. The internal has parameters for my dependencies while the private constructor has no parameters and makes a call to BuildUp to use setter injection. As-is the code crashes on me with the following error:

StructureMap Exception Code:  245
Error while trying to create an InstanceBuilder for My.Namespace.And.Class, My.Assembly, Version=5.0.0.0, Culture=neutral, PublicKeyToken=null
at StructureMap.Graph.PluginCache.<.cctor>b__1(Type t) in c:\code\structuremap\Source\StructureMap\Graph\PluginCache.cs:line 40
at StructureMap.Util.Cache`2.get_Item(KEY key) in c:\code\structuremap\Source\StructureMap\Util\Cache.cs:line 82
at StructureMap.Graph.PluginCache.FindBuilder(Type pluggedType) in c:\code\structuremap\Source\StructureMap\Graph\PluginCache.cs:line 52
at StructureMap.Container.BuildUp(Object target) in c:\code\structuremap\Source\StructureMap\Container.cs:line 243
at StructureMap.ObjectFactory.BuildUp(Object target) in c:\code\structuremap\Source\StructureMap\ObjectFactory.cs:line 297

Object reference not set to an instance of an object.
at StructureMap.Construction.ConstructorFunctionBuilder`1.CreateBuilder(Plugin plugin) in c:\code\structuremap\Source\StructureMap\Construction\ConstructorFunctionBuilder.cs:line 25
at StructureMap.Construction.BuilderCompiler.FuncCompiler`1.CreateBuilder(Plugin plugin) in c:\code\structuremap\Source\StructureMap\Construction\BuilderCompiler.cs:line 51
at StructureMap.Construction.BuilderCompiler.CreateBuilder(Plugin plugin) in c:\code\structuremap\Source\StructureMap\Construction\BuilderCompiler.cs:line 12
at StructureMap.开发者_如何学编程Graph.PluginCache.<.cctor>b__1(Type t) in c:\code\structuremap\Source\StructureMap\Graph\PluginCache.cs:line 36

If I change the default constructor so it's public instead of private, or even internal, then everything works as expected. Is this the intended behavior with private and internal constructors or is this a bug?


Yes, you need a public constructor for structuremap to auto-configure the instance.

IMHO if you're making explicit calls to the container (BuildUp) then you're adding coupling to the DI, which defeats some of the purpose of DI (to remove coupling). I much prefer to stick to simple constructor injection, then If I DO for some reason need to fill dependencies explicitly, just call ask the container for the concrete class (ObjectFactory.GetInstance<Class>()), and it will auto-fill the dependencies in the most complex public constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜