.net - Structuremap - 多个接口(interface)实现

标签 .net asp.net-mvc-3 structuremap

我对 Structuremap 完全陌生,并且对如何连接具有多个实现的接口(interface)感到困惑。

假设我有 Controller1Controller2 .我有 Interface1由两个单独的类实现,Class1ForInterface1Class2ForInterface1 .在 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/

相关文章:

c# - 为多行 lambda 创建表达式树的 Roslyn 流畅语法

c# - 设计以避免派生类中的类型转换?

asp.net-mvc-3 - 将 MetadataType 添加到 C# 中的派生类

css - 为什么 :active property work in Asp. 不是 net MVC

c# - IOC 在服务层注册存储库,在表示层注册服务

structuremap - 如何在 OpenRasta 中使用 StructureMap

c# - 事件处理程序的匿名方法不是泄漏?

c# - 如何在 .net 中将 json 解析为 html

c# - 无法在 Razor View 中设置 javascript 对象

asp.net-web-api - 如何在 StructureMap ServiceActivator 中使用 Container 而不是 ObjectFactory?