Click here to Skip to main content
15,076,130 members
Articles / General Programming / Architecture
Tip/Trick
Posted 29 Jul 2017

Stats

16.7K views
1 bookmarked

How to Locate a Service in Unity

Rate me:
Please Sign up or sign in to vote.
4.41/5 (8 votes)
29 Jul 2017CPOL
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.

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dirk Bahle
Germany Germany
The Windows Presentation Foundation (WPF) and C# are among my favorites and so I developed Edi

and a few other projects on GitHub. I am normally an algorithms and structure type but WPF has such interesting UI sides that I cannot help myself but get into it.

https://de.linkedin.com/in/dirkbahle

Comments and Discussions

 
QuestionAn Alternative Approach. Pin
George Swan31-Jul-17 9:17
MemberGeorge Swan31-Jul-17 9:17 
AnswerRe: An Alternative Approach. Pin
Dirk Bahle1-Aug-17 10:19
MemberDirk Bahle1-Aug-17 10:19 
Question[My vote of 1] Seriously? Pin
spi31-Jul-17 1:58
professionalspi31-Jul-17 1:58 
AnswerRe: [My vote of 1] Seriously? Pin
Dirk Bahle31-Jul-17 4:47
MemberDirk Bahle31-Jul-17 4:47 
GeneralRe: [My vote of 1] Seriously? Pin
spi22-May-18 3:26
professionalspi22-May-18 3:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.