我的演示代码很简单
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();
则没有问题
我不清楚原因,因为我们使用的是工厂模式,谁能给我一些原因吗?
最佳答案
看看通用的 BuildUp-Method过载。
Unity 使用指定的 T 类型来检查它的属性并确定要注入(inject)的依赖项。
在您的情况下,您没有明确指定 T 而是依赖 type inference ,它解析为类“Base”(因为参数变量类型是“Base”类型)。
因此,要么相应地声明您的变量,要么通过 non-generic version 尝试另一种方法:
container.BuildUp(typeof(Derived), bd);
或
container.BuildUp(bd.GetType(), bd); //which resolves to "Derived"
这在给定的示例中目前意义不大,但我希望为简单起见对您的示例进行分解。
关于c# - 带有 Unity Buildup<T> 问题的工厂模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43785352/