0

I am playing around with Unity Library, as at my workplace it is highly used, so wanted to understand its different behaviours.

I am confused about BuildUp and Resolve because they seem to do same thing so i am not getting when it is suitable to use BuildUp and when Resolve.

Am i missing something ?

Here is example :

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

Example using 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>();

and here is example using 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);
Jamiec
  • 133,658
  • 13
  • 134
  • 193
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160

1 Answers1

2

Resolve is used to instantiate an instance of an object, and inject dependencies.

BuildUp is used to inject dependencies into an existing instance of an object.

Jamiec
  • 133,658
  • 13
  • 134
  • 193