Reputation: 88
I ran into a strange problem yesterday. I built a makeshift viewmodel locator style system yesterday using ninject as its di container. I then tried to have it resolve a moq mock implementation of a data repository interface to feed into the viewmodels through constructor injection. But, I keep getting the following exception from moq at design time.
Error 2 Unable to cast object of type 'Castle.Proxies.IADEmployeeRepoProxy_1' to type 'MVVMSupport.TestHarness.Data.IADEmployeeRepo'. D:\Users\kicksagnome\Desktop\MVVMSupport\MVVMSupport.TestHarness\App.xaml 16 13 MVVMSupport.TestHarness
Mock<IADEmployeeRepo> repo = new Mock<IADEmployeeRepo>();
repo.Setup<List<ADEmployee>>(r => r.GetAllEmployees())
.Returns(new List<ADEmployee>() { new ADEmployee() { FirstName = "Ryan Butcher" } });
Bind<IADEmployeeRepo>().ToConstant(repo.Object); //Also tried Bind<IADEmployee>().ToMethod(context => repo.Object);
It runs fine the first load of the designer and fails every time design data is changed and I rebuild the solution.
I recognize this isn't how moq is meant to be used so the question is...
1.) Is there a way to fix this issue?
2) How should I be adding design time data?
Upvotes: 2
Views: 710
Reputation: 11763
Well, you have several options. You could have different options in your View Model depending on "IsInDesignMode", and have your design data reside there. That would be your quick and dirty option.
A better option would be to have a DataService, and a Mock one (or DesignDataService), and in your ViewModelLocator, you'll use that in your "IsInDesignMode".
From there, just add whatever you need to mock to the Interface of the DataService, this service will be injected into your view model on construction, and you can then simple have something like:
MyData = DataService.GetData();
In the real data service, you'll fetch your data, and in the design/mock one, you can fake to your liking, having your design data displayed easily.
Let me know if you have any other questions, or need more code for the example.
Upvotes: 1