问题描述
|
我对Structuremap完全陌生,并且对如何连接具有多个实现的接口感到困惑。
可以说我有
Controller1
和Controller2
。我有由两个单独的类Class1ForInterface1
和ѭ4implemented实现的Interface1
。在Controller1
中,我要注入Class1ForInterFace1
,在Controller2
中,我要注入Class2ForInterface1
。
如何将其与structuremap连接?看来我只能有一个接口到具体类型的映射?
谢谢!
解决方法
可能有多个类使用structuremap实现相同的接口。
如果您为映射命名,则以后可以使用该名称检索它们。
For<MyInterface>().Add<Class1ForMyInterface>().Named(\"Class1\");
For<MyInterface>().Add<Class2ForMyInterface>().Named(\"Class2\");
如果您随后想要Class1ForMyInterface,则可以致电
container.GetInstance<MyInterface>(\"Class1\");
还有几种方法可以在容器中映射所有这些内容
For<IController>().Add<Controller1>().Ctor<MyInterface>().Is(i => i.GetInstance<MyInterface>(\"Class1\"));
或者,如果您保留注册类型时返回的smartinsatance,则可以在映射中使用它。
var class1 = For<MyInterface>().Add<Class1ForMyInterface>().Named(\"Class1\");
For<IController>().Add<Controller1>().Ctor<MyInterface>().Is(class1);