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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With