开发者

Using Moq at Blend design time

This might be a bit out there, but suppose I want to use Moq in a ViewModel to create some design time data, like so:

public class SomeViewModel
{
   public SomeViewModel(ISomeDependency dependency)
   {
      if (IsInDesignMode)
      {
         var mock = new Mock<ISomeDependency>();
         dependency = mock.Object; // this throws!  
      }
   }
}

The mock could be set up to do some stuff,开发者_开发问答 but you get the idea.

My problem is that at design-time in Blend, this code throws an InvalidCastException, with the message along the lines of "Unable to cast object of type 'Castle.Proxies.ISomeDependencyProxy2b3a8f3188284ff0b1129bdf3d50d3fc' to type 'ISomeDependency'." While this doesn't necessarily look to be Moq related but Castle related, I hope the Moq example helps ;)

Any idea why that is?

Thanks!


I'm having a similar issue, except that the cast is coming from a dynamically generated assembly (Blend_RuntimeGeneratedTypesAssembly) type that is masquerading as one of my types.

For no apparent reason.

Which is driving me CRAZY.


I used to think that I needed to do this sort of trick but after much experiementing and searching about, discovered that Blend 4 now can create design time sample datacontexts based on an existing class.

This effectively gives you a dummy class that looks just like your VM class so that you can add your binding etc.

It works well enough that this is the technique we now recommend.

A possible disadvantage with this is that if you need your real VM to perform some sort of interactivity then the proxy of course can't do that - you'd have to manually change values, or swap to another design time object. But in practice, I've rarely encountered this scenario. Most of the time, you set the state of the VM and then take ages getting the look right.


Update: released on github: https://github.com/GeniusCode/GeniusCode.Components.DynamicDuck

I also ran into a similar problem when trying to use castle to mock viewmodels at design time. We wrote our own msil duck / mock library, and it works well for that purpose.

I blogged about it here: http://blogs.geniuscode.net/JeremiahRedekop/?p=255

We are working to release the library under MS-PL and deploy on GitHub.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜