Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. WPF
  4. MVVM Dependency Injection with Service Locator

MVVM Dependency Injection with Service Locator

Scheduled Pinned Locked Moved WPF
wpfdotnetcomarchitecturetutorial
1 Posts 1 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    Kevin Marois
    wrote on last edited by
    #1

    I want to automatically bind Views to ViewModels that consume services. For example, my sample app uses an RSS Service to get RSS feeds. In production I want the concrete service. If I want to run Unit Tests on it, I want to pass in a mock service.

    public MainWindowViewModel(IRssService rssService)
    {
    _rssService = rssService;
    }

    First, I created a Service Locator class. This class works fine:

    public class ServiceLocator : IServiceLocator
    {
    private IDictionary<object, object> _services;

    public ServiceLocator(bool isTestMode)
    {
    	\_services = new Dictionary<object, object>();
    
    	if (isTestMode)
    	{
    		// Add mock services to the dictionary
    		this.\_services.Add(typeof(IRssService), new FakeRssService());
    	}
    	else
    	{
    		// Add Runtime services to the dictionary
    		this.\_services.Add(typeof(IRssService), new RssService());
    	}
    }
    
    public T Get<T>()
    {
    	try
    	{
    		return (T)\_services\[typeof(T)\];
    	}
    	catch (KeyNotFoundException)
    	{
    		throw new ApplicationException("The requested service is not registered");
    	}
    }
    

    }

    Next, I created a ViewModelLocator class

    public class ViewModelLocator
    {
    // List of ViewModels
    private List<object> _viewModels;

    // Service Locator
    private IServiceLocator \_serviceLocator;
    
    public bool IsTestMode { get; set; }
    
    // Main Window View Model
    public MainWindowViewModel MainWindowVM 
    {
        get { return Get<MainWindowViewModel>(); }
    }
    
    //CTOR
    internal ViewModelLocator()
    {
    	\_serviceLocator = new ServiceLocator(IsTestMode);
    
    	\_viewModels = new List<object>();
    
    	\_viewModels.Add(new MainWindowViewModel(\_serviceLocator.Get<IRssService>()));
    }
    
    // Get to retrieve the VM
    public T Get<T>()
    {
        try
        {
            var vm = (T)\_viewModels.FirstOrDefault(x => x is T);
            return vm;
            //return (T)\_viewModels\[typeof(T)\];
        }
        catch (KeyNotFoundException)
        {
            throw new ApplicationException("The requested service is not registered");
        }
    }
    

    }

    Next I wired it all up XAML - App

    <Application x:Class="DIExample1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DIExample1"
    StartupUri="MainWindowView.xaml">

    <Applic
    
    1 Reply Last reply
    0
    Reply
    • Reply as topic
    Log in to reply
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes


    • Login

    • Don't have an account? Register

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • World
    • Users
    • Groups