我正在玩Unity库,因为在我的工作场所它很常用,所以想了解它的不同行为。
我对BuildUp
和Resolve
感到困惑,因为它们似乎做同样的事情,所以当适合使用BuildUp
和Resolve
时,我没有得到。< / p>
我错过了什么吗?
以下是示例:
public class Decorations
{
public string Header { get; set; }
public string Footer { get; set; }
}
public class Printer
{
internal void Print(string message)
{
Console.WriteLine("HEADER: {0}", this.Decorations != null
&& this.Decorations.Header != null
? this.Decorations.Header
: string.Empty);
Console.WriteLine(message);
Console.WriteLine("FOOTER: {0}", this.Decorations != null
&& this.Decorations.Footer != null
? this.Decorations.Footer
: string.Empty);
}
[Dependency]
public Decorations Decorations { get; set; }
}
public class ClassA
{
public void Print(Printer printer, IUnityContainer container)
{
container.BuildUp(printer);
printer.Print("Hello from ClassA");
container.Teardown(printer);
}
}
使用Resolve<T>()
的示例:
var printer = new Printer();
var containerA = new UnityContainer();
containerA.RegisterInstance(new Decorations
{
Header = "I am HEADER from Decorations #1",
Footer = "I am FOOTER from Decorations #1"
});
var a = new ClassA();
var objClassA = containerA.Resolve<Decorations>();
以下是使用BuildUp()
的示例:
var printer = new Printer();
var containerA = new UnityContainer();
containerA.RegisterInstance(new Decorations
{
Header = "I am HEADER from Decorations #1",
Footer = "I am FOOTER from Decorations #1"
});
var a = new ClassA();
var objClassA = containerA.Resolve<Decorations>();
a.Print(printer, containerA);
答案 0 :(得分:2)
Resolve
用于实例化对象的实例,并注入依赖项。
BuildUp
用于将依赖项注入对象的现有实例。