不允许将默认实例注册到StructureMap

时间:2018-10-19 09:39:05

标签: c# dependency-injection ioc-container structuremap

我们有一个由两个类实现的接口:

public interface ISomething { void DoSomething(); }
public class Something1 : ISomething { public void DoSomething() {...} }
public class Something2 : ISomething { public void DoSomething() {...} }

这些接口由两个不同的模块使用。 Module1需要Something1,而Module2需要Something2

public class Module1(ISomething something) { something.DoSomething(); }
public class Module2(ISomething something) { something.DoSomething(); }

我们在注册表中进行了设置:

For<Module1>().Use<Module1>().Ctor<ISomething>().Is<Something1>();
For<Module2>().Use<Module2>().Ctor<ISomething>().Is<Something2>();

但是,当它运行时,会出现以下错误:

  

没有注册默认实例,并且无法自动确定类型为“ ISomething”的

如果我们创建并注册一个默认类,那么它将起作用,并且不会出现上述错误:

public class DefaultSomething : ISomething { public void DoSomething() {...} }
For<ISomething>().Use<DefaultSomething>();

该接口的所有用法都在注册表中配置,我们不想指定默认值,但是似乎您必须告诉StructureMap使用什么,即使它永远不需要使用它。是否可以不必指定默认实例?

谢谢:)

0 个答案:

没有答案