加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

.net – Structuremap – 多个接口实现

发布时间:2020-12-16 04:33:09 所属栏目:asp.Net 来源:网络整理
导读:我对Structuremap完全不熟悉,并且对如何连接具有多个实现的接口感到困惑. 让我们说我有Controller1和Controller2.我有Interface1,它由两个独立的类Class1ForInterface1和Class2ForInterface1实现.在Controller1中我希望注入Class1ForInterFace1,而在Controll
我对Structuremap完全不熟悉,并且对如何连接具有多个实现的接口感到困惑.

让我们说我有Controller1和Controller2.我有Interface1,它由两个独立的类Class1ForInterface1和Class2ForInterface1实现.在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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读