Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Microsoft Unity?

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.

like image 908
mishap Avatar asked Feb 03 '23 11:02

mishap


1 Answers

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.

like image 132
Mark Seemann Avatar answered Feb 08 '23 14:02

Mark Seemann