2017-05-04 23 views
3

我的演示代码很简单工厂模式与统一集结<T>麻烦

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(); 
    } 
} 

在派生类中的DerivedDecorations无法在上述情况下

得到解决,如果我们的代码更改为Derive bd = new Derive();没有问题

我不清楚原因,因为我们使用工厂模式,有没有人能给我一些原因呢?

+0

为什么你不只是'导出temp = new Derive(); container.BuildUp(temp);导出bd = temp; ' –

+0

因为我们使用工厂....代码就像Base b = GetDerived().... – allencharp

回答

2

看看通用的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" 

其在给定的例子,使目前没有什么意义,但我希望你的样品为简单起见分解。

+0

非常有帮助,谢谢! – allencharp

+0

另一个提示:也许可能不是“buildUp”现有的实例,而是让工厂通过容器创建一个实例,在这种情况下,完整类型是已知的。 这会推断出“Derived”也需要在容器中注册。 –