我对 Structuremap 完全陌生,并且对如何连接具有多个实现的接口(interface)感到困惑。
假设我有 Controller1
和 Controller2
.我有 Interface1
由两个单独的类实现,Class1ForInterface1
和 Class2ForInterface1
.在 Controller1
我要Class1ForInterFace1
注入(inject) Controller2
我要Class2ForInterface1
注入(inject)。
我如何将它与结构图连接起来?似乎我只能将接口(interface)映射到具体类型?
谢谢!
最佳答案
可以有多个类使用结构映射实现相同的接口(interface)。
如果您为映射命名,您可以稍后使用该名称检索它们。
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"));
或者,如果您保留注册类型时返回的 smartinstance,则可以在映射中使用它。
var class1 = For<MyInterface>().Add<Class1ForMyInterface>().Named("Class1");
For<IController>().Add<Controller1>().Ctor<MyInterface>().Is(class1);
关于.net - Structuremap - 多个接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6459306/