【问题标题】:Use dependency injection with specific instance - MS Unity对特定实例使用依赖注入 - MS Unity
【发布时间】:2013-04-21 08:58:53
【问题描述】:

我正在编写基于 PRISM 的 MVVM 应用程序。 那些天我在学习 PRISM,我有一个关于 UnityContainer 的技术问题。

在我使用container.Resolve 时有什么方法可以注入特定的实例?

我会尝试举例说明。

让我们注册下一个类型:

var container = new UnityContainer();
container
    .RegisterType(typeof(ISomeClass), typeof(SomeClass))

// with string
container
    .RegisterType(typeof(IExample), typeof(Example), "SpecificExampleInstance") 
// without string
container
    .RegisterType(typeof(IExample), typeof(Example)); 

SomeClass的构造函数获取IExample作为入参。

现在我想解析SomeClass 的实例,但告诉“容器”将SomeClass 构造函数注入IExample 的实例-“SpecificExampleInstance”(在上面代码的第 3 行注册的实例)而不是IExample - 不带字符串(在上述代码第 4 行注册的那个 - 不带字符串)

我希望我的问题足够清楚,如果没有,请告诉我,我会尝试改变表述。

谢谢

【问题讨论】:

    标签: mvvm prism unity-container


    【解决方案1】:

    一种选择是使用Dependency 属性:

    public class SomeClass
    {
       public SomeClass([Dependency("SpecificExampleInstance")] IExample myExample)
       { 
          // work with the service here
       }
    } 
    

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      相关资源
      最近更新 更多