【发布时间】: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