Created
April 28, 2010 17:58
-
-
Save jpoehls/382457 to your computer and use it in GitHub Desktop.
simple ViewModel locator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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