2

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?

4

1 回答 1

1

好吧,你有几个选择。根据“IsInDesignMode”,您可以在视图模型中有不同的选项,并将您的设计数据保存在那里。那将是您快速而肮脏的选择。

更好的选择是拥有一个 DataService 和一个 Mock 服务(或 DesignDataService),然后在您的 ViewModelLocator 中,您将在“IsInDesignMode”中使用它。

从那里,只需将您需要模拟的任何内容添加到 DataService 的接口,该服务将在构建时注入您的视图模型,然后您可以简单地拥有类似的东西:

MyData = DataService.GetData();

在真实数据服务中,您将获取您的数据,而在设计/模拟服务中,您可以根据自己的喜好伪造,让您的设计数据轻松显示。

如果您有任何其他问题,或者需要更多示例代码,请告诉我。

于 2013-10-07T04:38:46.010 回答