首页 > 解决方案 > 温莎城堡中的这个等价物是什么?

问题描述

假设我有例如:

public interface IYetAnotherInterface : IMyBaseInterface
public class JustAClass: IYetAnotherInterface

使用 Unity DI 容器这是有效的:

container.RegisterType<IMyBaseInterface, IYetAnotherInterface>();
container.RegisterType<IYetAnotherInterface, JustAClass>();

如何使用温莎城堡做到这一点?这失败了:

container.Register(
   Component
      .For<IMyBaseInterface>()
      .ImplementedBy<IYetAnotherInterface >());

container.Register(
   Component
      .For<IYetAnotherInterface >()
      .ImplementedBy<JustAClass>());

我正在尝试解决 ctor 中的 IYetAnotherInterface,例如

public Foo(IYetAnotherInterface i, ...)

标签: c#.netunity-containercastle-windsor

解决方案


我不确定这container.RegisterType<Interface1, Interface2>();在 Unity 中做了什么。看起来它连接了一个组件来解决另一个问题?

如果是这种情况,您有两个选择。

  • 如果您想拥有两个组件,请遵循@vzwick 的回答。

  • 如果您只需要一个组件,请使用以下内容。

.

Component
   .For<IMyBaseInterface, IYetAnotherInterface>()
   .ImplementedBy<JustAClass>()

因此,在第一个选项中,您最终会得到两个独立的组件,它们都由 支持JustAClass,每个都公开一个服务接口:一个 for IMyBaseInterface,另一个 for IYetAnotherInterface

在第二个选项中,您最终会得到一个组件,同时暴露IMyBaseInterfaceIYetAnotherInterface

该文档对这些概念有很好的解释,我强烈建议您熟悉它。


推荐阅读