Convention over Configuration

Aug 13, 2012 at 6:28 AM

I keep forgetting to add the View routes in the code behind and thought I should do something about it.

In each project (xap) my Views live in a namespace of solution.project.Views and they all finish with the word View.  So I have

WOL.Parties.Views.AddressView and

WOL.Parties.CompanyStandardView and so on

Every View Model follows this pattern


I want to iterate over all the exported Views and find if a ViewModel exists whose name is

ViewName.Replace("View", "ViewModel")

Easy enough, but the Lazy arrays ViewModelRouter.Views and ViewModels are not in the IFluentViewModelRouter interface (or the non-fluent equivalent).  They are public in the defining class, just not available through an [Import] of IFluentViewModelRouter.

To prove my concept I added

List<ViewModelRoute> RouteList { get; }
Lazy<Control, IExportAsViewMetadata>[] Views { get; set; }
Lazy<IViewModel, IExportAsViewModelMetadata>[] ViewModels { get; set; }

to the bottom of Jounce.Core.ViewModel.IFluentViewModelRouter and then I could have

public class InitializeViewMapping : IModuleInitializer
    public IFluentViewModelRouter Router { get; set; }

    public Boolean Initialized { get; private set; }

    public void Initialize()
        foreach (var view in Router.Views)
            var viewName = view.Metadata.ExportedViewType;
            var viewModelName = viewName.Replace("View", "ViewModel");
            if (Router.ViewModels.Any(vm => vm.Metadata.ViewModelType == viewModelName))
                if (!Router.RouteList.Any(route => route.ViewModelType == viewModelName && route.ViewType == viewName))
                    Router.RouteViewModelForView(viewModelName, viewName);

        Initialized = true;

Now my Views are wired to my ViewModels automatically as long as I follow the naming convention.

Question -  Is there a better way that does not involve modifying the definition of IFluentViewModelRouter?