9

I'm looking for some basic examples / explanations of Unity. I have hard time grasping the concept. I do have basic understanding of the Injection pattern as it seems that Unity is tightly related to it. I appreciate any help.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
mishap
  • 8,176
  • 14
  • 61
  • 92

3 Answers3

11

Unity is one of several DI Containers for .NET. It can be used to compose object graphs, when the types in question follow the Dependency Inversion Principle.

The easiest way to do that is to use the Constructor Injection pattern:

public class Foo : IFoo
{
    private readonly IBar bar;

    public Foo(IBar bar)
    {
        if (bar == null)
            throw new ArgumentNullException("bar");

        this.bar = bar;
    }

    // Use this.bar for something interesting in the class...
}

You can now configure Unity in the application's Composition Root:

container.RegisterType<IFoo, Foo>();
container.RegisterType<IBar, Bar>();

The is the Register phase of the Register Resolve Release pattern. In the Resolve phase the container will Auto-wire the object graph without further configuration:

var foo = container.Resolve<IFoo>();

This works automatically because the static structure of the classes involved includes all the information the container needs to compose the object graph.

Community
  • 1
  • 1
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • 10
    To add to Mark's answer (hope he doesn't mind), if you want to learn more about Dependency Injection, there's a really good book called "Dependency Injection in .NET" written by Mark himself. http://www.manning.com/seemann/ – Phill Nov 22 '11 at 09:10
  • 1
    @phill: please don't do that. Mark hates it when people refer to his book :-) – Steven Nov 22 '11 at 17:55
0

Check here: Microsoft Unity 2.0 – April 2010

Yuriy Rozhovetskiy
  • 22,270
  • 4
  • 37
  • 68