asp.net-mvc-3 – 依赖注入与多个类实现的接口
|
更新:有没有办法在Windsor之外的IoC框架中实现我想要做的工作? Windsor将处理控制器,但不会解决任何其他事情.我确定这是我的错,但是我正在按照这个教程进行逐字追踪,并且对象不能用ctor注入来解析,尽管做了寄存器和解析,它们仍然是空的.我已经废除了我的DI代码,现在手动注入,因为该项目是时间敏感的.希望在截止日期之前完成DI. 我有一个解决方案,有多个类都实现相同的接口 作为一个简单的例子,Interface public interface IMyInterface {
string GetString();
int GetInt();
...
}
具体课 public class MyClassOne : IMyInterface {
public string GetString() {
....
}
public int GetInt() {
....
}
}
public class MyClassTwo : IMyInterface {
public string GetString() {
....
}
public int GetInt() {
....
}
}
现在这些类将在需要时被注入到它们之上的层中,如: public class HomeController {
private readonly IMyInterface myInterface;
public HomeController() {}
public HomeController(IMyInterface _myInterface) {
myInterface = _myInterface
}
...
}
public class OtherController {
private readonly IMyInterface myInterface;
public OtherController() {}
public OtherController(IMyInterface _myInterface) {
myInterface = _myInterface
}
...
}
两个控制器都注入了相同的界面. 当我在IoC中使用适当的具体类来解决这些接口时,如何区分HomeController需要MyClassOne和OtherController的实例需要MyClassTwo的实例? 如何将两个不同的具体类绑定到IoC中的同一个接口?我不想创建2个不同的界面,因为它打破了DRY规则,没有任何意义. 在温莎城堡我会有这样的两行: container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassOne>()); container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassTwo>()); 这将无法正常工作,因为我只会获得MyClassTwo的副本,因为它是为接口注册的最后一个. 就像我说的那样,我不会如何做到这一点,而不是为每个具体的创建特定的接口,这样做不仅破坏了干规则,还打破了基本的OOP.我该如何实现? 基于Mark Polsen的回答更新 这是我当前的IoC,那么.Resolve语句将在哪里?我没有看到Windsor文档中的任何内容 public class Dependency : IDependency {
private readonly WindsorContainer container = new WindsorContainer();
private IDependency() {
}
public IDependency AddWeb() {
...
container.Register(Component.For<IListItemRepository>().ImplementedBy<ProgramTypeRepository>().Named("ProgramTypeList"));
container.Register(Component.For<IListItemRepository>().ImplementedBy<IndexTypeRepository>().Named("IndexTypeList"));
return this;
}
public static IDependency Start() {
return new IDependency();
}
}
解决方法您应该能够通过命名组件注册完成它.container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassOne>().Named("One"));
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassTwo>().Named("Two"));
然后解决它们 kernel.Resolve<IMyInterface>("One");
要么 kernel.Resolve<IMyInterface>("Two");
See: To specify a name for the component (编辑:台州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc – 是否有一个ASP MVC与JSTL标签等效?
- asp.net – 我如何使用AJAX来确定用户的会话是否已过期,然后
- asp.net-mvc – MVC4部分视图没有将值加载到“容器”模型中
- asp.net-mvc-2 – MVC源代码单例模式
- asp.net-mvc – IIS显示服务器错误而不是自定义错误
- asp.net-mvc-routing – 在MVC 6控制器中使用urlhelper生成
- asp.net-mvc – 如何组合两个dataTextFields的SelectList描
- 将ASP.NET身份与核心域模型分离 – 洋葱架构
- 在ASP.Net MVC应用程序中放置初始化代码的位置?
- Asp.net mvc验证用户登录之Forms实现详解
