使用Caliburn.Micro时,AutoMapper在设计时不起作用

时间:2018-08-16 12:05:41

标签: c# automapper caliburn.micro design-time

背景

我正在使用WPF和Caliburn.Micro为现有CLI应用程序构建用户界面。由于提供了许多DTO对象,因此我使用AutoMapper将数据传递到支持PropertyChanged通知的模型(使用Caliburn.Micro的PropertyChangedBase)。

我在Bootstrapper#Configure方法内设置AutoMapper,如下所示:

Mapper.Initialize(
    config => config.CreateMap<ModelA, ModelB>()
);

并且正在我的ViewModel中使用它:

private static ModelA[] source = new[] {
    new ModelA {
        Name = "foo"
    },
    new ModelA {
        Name = "bar"
    }
};

public BindableCollection<ModelB> Items { get; } = new BindableCollection<ModelB>(
    Mapper.Map<ModelA[], IEnumerable<ModelB>>(source)
);

问题描述

问题是,当我为Caliburn.Micro使用Design Time support时,DataMapper仅在启动Visual Studio时起作用。

xmlns:vm="clr-namespace:CaliburnAutoMapperBug.ViewModels"
xmlns:cal="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro.Platform"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=vm:ShellViewModel, IsDesignTimeCreatable=True}"
cal:Bind.AtDesignTime="True">

当您更改ViewModel中的任何值时,更改不会被投影到设计器中,并且一旦设计器抛出错误(图像)并停止渲染,最终您运行应用程序后,一切都会在运行时正常进行。

图片

enter image description here

如何复制

  1. 克隆problem example存储库
  2. 打开解决方案
  3. 在设计器中打开Views / ShellView.xaml
  4. 此时,设计人员应该可以正常工作并在StackPanel中显示3个项目
  5. 打开ViewModels / ShellViewModel.cs
  6. 对源数组进行任何更改(更改名称,删除或添加项目)
  7. 运行应用程序,您应该看到所做的更改
  8. 回到Views / ShellView.xaml的设计器
  9. 设计器将在第10行显示错误:“找到了未映射的成员...”

1 个答案:

答案 0 :(得分:1)

我还没有完全解决设计时的问题,但是在suggested下切换到基于实例的AutoMapper配置解决了该异常。

protected override void Configure() {
    container = new SimpleContainer();
    container.Singleton<IWindowManager, WindowManager>();
    container.Singleton<IEventAggregator, EventAggregator>();
    container.PerRequest<IShell, ShellViewModel>();

    MapperConfiguration config = new MapperConfiguration(cfg => {
        cfg.CreateMap<Core.ProjectDto, Models.Panel.Project>();
    });

    container.RegisterInstance(
        typeof(IMapper),
        "automapper",
        config.CreateMapper()
    );
}