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;
interface IFoo
{
}
public class Foo : IFoo
{ }
class Program
{
static void Main(string[] args)
{
UnityServiceLocator locator = new UnityServiceLocator(ConfigureUnityContainer());
ServiceLocator.SetLocatorProvider(() => locator);
Console.WriteLine(Resolve());
Console.ReadKey();
}
private static bool Resolve()
{
var a = ServiceLocator.Current.GetInstance<IFoo>();
var b = ServiceLocator.Current.GetInstance<IFoo>();
return a.Equals(b);
}
private static IUnityContainer ConfigureUnityContainer()
{
UnityContainer container = new UnityContainer();
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.