asp.net-mvc-3 – 依赖注入与多个类实现的接口

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 依赖注入与多个类实现的接口前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
更新:有没有办法在Windsor之外的IoC框架中实现我想要做的工作? Windsor将处理控制器,但不会解决任何其他事情.我确定这是我的错,但是我正在按照这个教程进行逐字追踪,并且对象不能用ctor注入来解析,尽管做了寄存器和解析,它们仍然是空的.我已经废除了我的DI代码,现在手动注入,因为该项目是时间敏感的.希望在截止日期之前完成DI.

我有一个解决方案,有多个类都实现相同的接口

作为一个简单的例子,Interface

public interface IMyInterface {
    string GetString();
    int GetInt();
   ...
}@H_301_7@ 
 

具体课

public class MyClassOne : IMyInterface {
    public string GetString() {
        ....
    }
    public int GetInt() {
        ....
    }
}

public class MyClassTwo : IMyInterface {
    public string GetString() {
        ....
    }
    public int GetInt() {
        ....
    }
}@H_301_7@ 
 

现在这些类将在需要时被注入到它们之上的层中,如:

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
    }
    ...
}@H_301_7@ 
 

两个控制器都注入了相同的界面.

当我在IoC中使用适当的具体类来解决这些接口时,如何区分HomeController需要MyClassOne和OtherController的实例需要MyClassTwo的实例?

如何将两个不同的具体类绑定到IoC中的同一个接口?我不想创建2个不同的界面,因为它打破了DRY规则,没有任何意义.

在温莎城堡我会有这样的两行:

container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassOne>());
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassTwo>());@H_301_7@ 
 

这将无法正常工作,因为我只会获得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();
    }
}@H_301_7@

解决方法

您应该能够通过命名组件注册完成它.
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassOne>().Named("One"));
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassTwo>().Named("Two"));@H_301_7@ 
 

然后解决它们

kernel.Resolve<IMyInterface>("One");@H_301_7@ 
 

要么

kernel.Resolve<IMyInterface>("Two");@H_301_7@ 
 

See: To specify a name for the component

原文链接:https://www.f2er.com/aspnet/246277.html

猜你在找的asp.Net相关文章