How to Locate a Service in Unity






4.41/5 (8 votes)
A simple example to get started with the Unity Container usually used in Prism
Introduction
I spent a considerable amount of time to find a simple example of a Unity service locator implementation on the level of the article written by Josh Smith and finally found it after a long time of searching in a blog post back in 2009. I re-post this content here with some hopefully helpful comments. Please be sure to read Josh's article if you are new to the service location pattern.
Using the Code
Just create a Console Type project and add the Unity package via Nuget. Next, you should be able to copy/paste the code below to inspect how things work on a simple object registration/resolution level in Unity.
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using System;
/// <summary>
/// Implements an interface for testing
/// </summary>
interface IFoo
{
}
/// <summary>
/// Implements a test class based on the <seealso cref="IFoo"/> interface.
/// This code requires the Unity package to be installed (e.g.: via Nuget).
/// </summary>
public class Foo : IFoo
{ }
/// <summary>
/// Source: https://blogs.msdn.microsoft.com/miah/2009/05/12/servicelocator-and-unity-be-careful/
/// </summary>
class Program
{
static void Main(string[] args)
{
UnityServiceLocator locator = new UnityServiceLocator(ConfigureUnityContainer());
ServiceLocator.SetLocatorProvider(() => locator);
Console.WriteLine(Resolve());
Console.ReadKey();
}
/// <summary>
/// Asks the Unity ServiceLocator to resolve two registered instances
/// and determines whether they are equal or not.
/// </summary>
/// <returns>True if all resolved instances are the same, otherwise false</returns>
private static bool Resolve()
{
var a = ServiceLocator.Current.GetInstance<IFoo>();
var b = ServiceLocator.Current.GetInstance<IFoo>();
return a.Equals(b);
}
/// <summary>
/// Constructs and configures a <seealso cref="IUnityContainer"/> and returns it.
/// </summary>
/// <returns></returns>
private static IUnityContainer ConfigureUnityContainer()
{
UnityContainer container = new UnityContainer();
//container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());
container.RegisterInstance<IFoo>(new Foo());
return container;
}
}
Points of Interest
Service Location is a must have pattern when it comes to architecturing large applications. Be sure to understand and apply this pattern whenever a service seems to be rightfully used in any application, be it Windows Form, WPF, UWP, or any other framework, or type of application.