无法使用StructureMap从私有或内部构造函数调用BuildUp

时间:2011-07-26 23:42:37

标签: c# dependency-injection structuremap

在我的一个类中,我有一个用于单元测试的内部构造函数,以及一个我的应用程序调用的私有构造函数。内部具有我的依赖项的参数,而私有构造函数没有参数,并调用BuildUp来使用setter注入。因为代码在我身上崩溃,出现以下错误:

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

如果我更改默认构造函数,使其为public而不是private,甚至是internal,那么一切都按预期工作。这是私有和内部构造函数的预期行为还是这个错误?

1 个答案:

答案 0 :(得分:6)

是,you need a public constructor用于自动配置实例的structuremap。

恕我直言,如果您正在对容器进行显式调用(BuildUp),那么您正在向DI添加耦合,这会破坏DI的某些目的(以消除耦合)。我更喜欢stick to simple constructor injection,然后如果由于某种原因我需要显式填充依赖项,只需调用请求容器的具体类(ObjectFactory.GetInstance<Class>()),它将自动填充依赖项中的依赖项。最复杂的公共构造函数。