【问题标题】:Unity Newbie QuestionUnity新手问题
【发布时间】:2010-11-05 16:24:28
【问题描述】:

我是第一次尝试使用 Unity,但我想我可能咬得比我能嚼的多。我们有一个 n 层应用程序,它有一个包含几个抽象类型的基础库,然后在它之上有几个特定于业务场景的库和具体类型。例如:抽象类型lead 有两种实现,一种在NewAutomotiveLibrary 中称为NewAutomotiveLead,另一种在AutomotiveFinanceLibrary 中称为AutomotiveFinanceLead。在基本库中,我们有一组适配器,它们对基本类型(如 Lead)执行逻辑。

我第一次尝试使用 Unity 返回一个接口 ILeadDuplication,当我在 ILeadDuplication 上调用 resolve 并传递“NewAutomotive”或“ AutomotiveFinance”(在容器上调用 RegisterType 时映射的名称)。像这样:

  using (IUnityContainer container = new UnityContainer())
  {
    container
      .RegisterType<ILeadDuplication, AutomotiveFinanceLeadDuplication>("AutomotiveFinance")
      .RegisterType<ILeadDuplication, NewAutomotiveLeadDuplication>("NewAutomotive");

    ILeadDuplication dupe = container.Resolve<ILeadDuplication>("AutomotiveFinance");
    Console.WriteLine(dupe.Created);
  }

注意:这是为了说明,因为库对 ILeadDuplication 的创建类一无所知,实际注册需要在配置文件中完成。

虽然这一切都很好,但我需要更进一步。调用 resolve 时,我需要能够传入 Lead 类型的参数,它是 NewAutomotiveLead 或 AutomotiveFinanceLead 的基本类型。

我需要知道 Unity 是否有可能以某种方式神奇地查看特定于具体实例 AutomotiveFinanceLead 的属性,例如 Lead 上不存在的“GrossMonthlyIncome”,并将其分配给新创建的 AutomotiveFinanceLeadDuplication 实例属性 GrossMonthlyIncome。

我实际上希望能够针对基础库中的 ILadDuplication 实例执行一组通用逻辑,即使生成的实例和映射的属性对它来说并不熟悉。

谢谢!

【问题讨论】:

    标签: .net architecture dependency-injection unity-container


    【解决方案1】:

    不太确定你在追求什么,但我猜你想在构建时传递一个依赖项。这可以通过多种方式完成,但这里有一个示例。

    [InjectionConstructor]
    public class MyClass([Dependency("Named")] MyOtherClass other)
    {
    
    }
    

    为了使其工作,名为“Named”的 MyOtherClass 依赖项必须通过配置或通过 RegisterType 方法添加到容器中。

    如果我不在基地,请告诉我,也许我可以为您提供进一步帮助...我在不同情况下使用 Unity 进行了很多工作,所以只要我知道您想要完成什么,我也许可以提供帮助你出去。

    【讨论】:

      【解决方案2】:

      我不明白你为什么希望容器承担这个责任。但我认为你可以这样做:

      就在您调用 Resolve() 以获取 ILeadDuplication 的新实例之前,您可以注册要使用的 Lead 实例和要使用的 GrossMonthlyIncome 的值:

        Lead lead = new NewAutomotiveLead()
        container.RegisterInstance<Lead>(lead);
        container.RegisterInstance<int>("GrossMonthlyIncome", lead.GrossMonthlyIncome);
        ILeadDuplication dupe = container.Resolve<ILeadDuplication>("AutomotiveFinance");
      

      如果具体类型具有名为“GrossMonthlyIncome”的依赖项,则该值将被注入那里。如果具体类型的构造函数采用 Lead 实例,则该实例将被注入到该构造函数参数中。

      【讨论】:

        猜你喜欢
        • 2012-07-16
        • 2010-12-08
        • 2011-08-13
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-08
        相关资源
        最近更新 更多