WPF/Prism: What is a UNITY Container?

Shai UI picture Shai UI · Jan 6, 2011 · Viewed 24k times · Source

Can someone please explain to me the notion of a Unity Container like I'm a 6 year old kid? How does it work and what does it do?

Answer

Femaref picture Femaref · Jan 6, 2011

This is a more technical description of the background, I hope you still find it useful.

Generally put, it is a DI (dependency injection) container.

Given the following class:

public class Sample
{
  Service a;

  public Sample()
  {
    a = new Service();
  }
}

The problem with that is that it initializes its own version of Service, making it very hard to adjust for code changes (ie. if you want to exchange Service with something different). Also it makes testing difficult.

To resolve that, don't actually create it yourself, but get it from the outside:

public class Sample
{
  Service a;

  public Sample(Service aService)
  {
    a = aService;
  }
}

Now you have taken the creation away from the class you can just put it in there from the outside, increasing testability and maintainability. However, you still have a dependency on the class Service. You aren't really interested in that specific class, but in the behaviour it offers - so you make in interface out of it.

public class Sample
{
  IService a;

  public Sample(IService aService)
  {
    a = aService;
  }
}

Now, you can replace the service with anything you like. For example, you have a class getting data from a server using a service. Now, you want to test only the data parsing and not the data fetching service - just create a class implementing the interface, serving static data - done!

Now, Unity comes into play. At the moment, you have to resolve the dependencies yourself. What unity does is simple - it takes all classes that have dependendencies and resolves those - so you can just call (pseudocode, I don't know unity):

UnityContainer uc = new UnityContainer();
var a = uc.GetService<IService>();

And it gets you the readily useable class.

What do we have achivied by that?

  • the code is more maintainable because you don't rely on specific types
  • the code is more testable
  • the application is easily expandable

As a summary: it helps creating better applications faster.