【问题标题】:Factory pattern with Unity Buildup<T> troubleUnity Buildup<T> 麻烦的工厂模式
【发布时间】:2017-10-02 18:41:43
【问题描述】:

我的演示代码很简单

using Microsoft.Practices.Unity;
using System;

public interface IDecorator
{
    string GetA();
}

public class Decorations:IDecorator
{

    public string GetA()
    {
        return "temp";
    }
}

public class Base
{

}

public class Derive : Base
{
    [Dependency]
    public IDecorator DerivedDecorations { get; set; }
}


public class Program
{
    private static void Main(string[] args)
    {

        Base bd = new Derive(); // here is the point

        var container = new UnityContainer();
        container.RegisterType<IDecorator, Decorations>();

        container.BuildUp(bd); // bd.DerivedDecorations is null

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}

Derive 类中的DerivedDecorations 在上述情况下无法解决

如果我们将代码更改为Derive bd = new Derive(); 就没有问题

我不清楚原因,因为我们使用的是工厂模式,谁能给我一些原因吗?

【问题讨论】:

  • 你为什么不直接做Derive temp = new Derive(); container.BuildUp(temp ); Derive bd = temp;
  • 因为我们使用 factory.... 代码类似于 Base b = GetDerived()....

标签: c# unity-container inject


【解决方案1】:

看看通用的BuildUp-Method 重载。

Unity 使用指定的 T 类型来检查它的属性并确定要注入的依赖项。

在您的情况下,您没有明确指定 T,而是依赖 type inference,它解析为“Base”类(因为参数变量类型是“Base”类型)。

因此,要么相应地声明您的变量,要么通过non-generic version 尝试另一种方法:

container.BuildUp(typeof(Derived), bd);

container.BuildUp(bd.GetType(), bd); //which resolves to "Derived"

在给定的示例中目前没有什么意义,但我希望为简单起见对您的示例进行分解。

【讨论】:

  • 另一个提示:也许可以不“构建”现有实例,而是让工厂通过容器创建实例,在这种情况下,完整类型是已知的。这会推断出“Derived”也需要在容器中注册。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 2018-11-04
相关资源
最近更新 更多