【问题标题】:Unity - Inject object of different classes for the same interface in a same classUnity - 为同一类中的同一接口注入不同类的对象
【发布时间】:2017-09-22 11:14:31
【问题描述】:

我有一个接口:IFoo 实现该接口的两个类:FooOne 和 FooTwo

还有一个类 ClassOne 在构造函数中接收 IFoo 参数。

我在 Classone 中有两个方法 MethodOne 和 methodTwo。

如果我调用 MethodOne,我需要 Classone 中的对象 FooOne

如果我调用 MethodTwo,我需要 Classone 中的对象 FooTwo

我如何配置统一,以便 ClassOne 接收用于 MethodOne 调用的 FooOne 实例,而 ClassOne 仅使用一个容器接收用于 MethodTwo 调用的 FooTwo?。

主要条件是我需要一次创建一个对象 FooOne 或 FooTwo。

【问题讨论】:

  • MethodOne 和 MethodTwo 所做的任何事情都应该放在我认为的 Foo 类中。
  • 我有这样的需求。
  • 你能展示ClassOne类吗?

标签: c# dependency-injection unity-container


【解决方案1】:

使用命名注册:

container.RegisterType<IFoo, FooOne>("one");
container.RegisterType<IFoo, FooTwo>("two");

//...

class Classone
{
    IFoo MethodOne()
    {
        return _container.Resolve<IFoo>("one");
    }

    IFoo MethodTwo()
    {
        return _container.Resolve<IFoo>("two");
    }
}

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2021-12-25
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多