Skip to content

Instantly share code, notes, and snippets.

@jpoehls
Created April 28, 2010 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpoehls/382457 to your computer and use it in GitHub Desktop.
Save jpoehls/382457 to your computer and use it in GitHub Desktop.
simple ViewModel locator
using System;
using System.ComponentModel.Composition;
using System.Collections.Generic;
using System.Linq;
namespace Samples
{
public class ViewModelIndexer
{
public ViewModelIndexer()
{
CompositionInitializer.SatisfyImports(this);
IsShared = false;
}
[ImportMany(typeof(ViewModelBase), AllowRecomposition = true)]
public IEnumerable<Lazy<ViewModelBase, IViewModelMetadata>> ViewModelsLazy { get; set; }
[ImportMany(typeof(ViewModelBase), AllowRecomposition = true)]
public IEnumerable<ExportFactory<ViewModelBase, IViewModelMetadata>> ViewModelsFactories { get; set; }
private ViewModelBase GetViewModel(string viewModel)
{
if (IsShared)
{
return ViewModelsLazy.Single(v => v.Metadata.Name.Equals(viewModel)).Value;
}
var context = ViewModelsFactories.Single(v => v.Metadata.Name.Equals(viewModel)).CreateExport();
return context.Value;
}
/// <summary>
/// True/False whether to return singleton view models
/// or a new instance per request.
/// </summary>
public bool IsShared { get; set; }
public ViewModelBase this[string viewModel]
{
get { return GetViewModel(viewModel); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment