WPF/Prism: What is a UNITY Container? WPF/Prism: What is a UNITY Container? wpf wpf

WPF/Prism: What is a UNITY Container?


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.


Unity Container is like a jar full of cookies , when you need a cookie you just ask jar to give you a cookie.

Each cookie is having some virtues like you can have a cookie but you can't eat it because it is very hard to eat (something like singleton)

when your mom creates a new cookie , she just put that cookie in the jar rather than giving you directly!


I recommend you to watch Mike Taulty's Prism video series

The first two chapters will answer your question, and you can watch the other chapters to learn Prism (although its version 2 and quite old, the basic principles remains the same...)

Good luck :)