2012-05-19

Articles

ServiceLocator

 

In the ServiceLocator, sometimes called ServiceProvider, services for interacting with the users or working with files can be registered. With this it is possible to create a clean MVVM environment and unit tests with faking user inputs. If you work with MVVM, you need such a ServiceProvier.

 

alt

 

Usage

<UserControl x:Class="DW.SharpTools.Demo.ServiceLocatorControl"
			 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
			 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
			 mc:Ignorable="d" 
			 d:DesignHeight="300" d:DesignWidth="300">
	<StackPanel>
		<Button HorizontalAlignment="Center" Content="Show Guid" Click="ShowGuid_Click" />
	</StackPanel>
</UserControl>
using System.Windows;
using System.Windows.Controls;

namespace DW.SharpTools.Demo
{
	public partial class ServiceLocatorControl : UserControl
	{
		public ServiceLocatorControl()
		{
			InitializeComponent();

			ServiceLocator.Register<IGuidFactory, GuidFactory>(Lifetime.Temporarily);
		}

		private void ShowGuid_Click(object sender, RoutedEventArgs e)
		{
			var guidFactory = ServiceLocator.Resolve<IGuidFactory>();
			MessageBox.Show(guidFactory.NewGuid());
		}
	}
}
namespace DW.SharpTools.Demo
{
	public interface IGuidFactory
	{
		string NewGuid();
	}
}
using System;

namespace DW.SharpTools.Demo
{
	public class GuidFactory : IGuidFactory
	{
		public string NewGuid()
		{
			return Guid.NewGuid().ToString();
		}
	}
}