我可能会说这一切都错了,但我认为我走的是正确的道路。我是第一次构建WPF应用程序,我仍然习惯于完成某些工作。
<Window.DataContext> <viewModels:UploaderViewModel> </viewModels:UploaderViewModel> </Window.DataContext>
注意:在我尝试进行注射之前这很好用
void App_Startup(object sender, StartupEventArgs eventArgs) { ContainerBootstrapper.BootstrapStructureMap(); ProcessStartupArguments(eventArgs); }
调用我的bootstrapper类:
public static class ContainerBootstrapper
{
public static void BootstrapStructureMap()
{
ObjectFactory.Initialize(
x => x.For<IVEDocumentService>().Use<VEDocumentService>()
);
}
}
然后让我的UploaderViewModel类将IVEDocumentService作为Constructor参数:
public UploaderViewModel(IVEDocumentService documentService)
{
_documentService = documentService;
//other unrelated code below this
}
我收到一条XAML错误,指出没有为ViewModel找到默认构造函数,这是有道理的,因为我没有UploaderViewModel()
,只有UploaderViewModel(IVEDocumentService documentService)
。
根据此SO Answer to a similar question,我尝试了:
void App_Startup(object sender, StartupEventArgs eventArgs) { ContainerBootstrapper.BootstrapStructureMap(); var uploaderViewModel = new UploaderViewModel(new Container().GetInstance<IVEDocumentService>()); Current.Resources["UploaderViewModel"] = uploaderViewModel; ProcessStartupArguments(eventArgs); }
DataContext="{StaticResource UploaderViewModel}"
声明<Window>
<viewModels:UploaderViewModel/>
声明执行此操作后,StructureMap现在抛出错误:
“StructureMap异常代码:202没有为。定义的默认实例 PluginFamily
答案 0 :(得分:1)
我明白了。我想我没有正确配置静态资源。使用StructureMap的解决方案是执行以下操作:
void App_Startup(object sender, StartupEventArgs eventArgs)
{
ContainerBootstrapper.BootstrapStructureMap();
//Other logic
}
public static void BootstrapStructureMap()
{
ObjectFactory.Initialize(x => x.For<IVEDocumentService>().Use<VEDocumentService>());
}
我将资源创建移到了这个类中:
public MainWindow()
{
var uploaderViewModel = new UploaderViewModel(ObjectFactory.GetInstance<IVEDocumentService>());
this.Resources["UploaderViewModel"] = uploaderViewModel;
InitializeComponent();
}
在<Window>
定义中,我设置了DataContext="{StaticResource UploaderViewModel}"
。
像魅力一样工作。我认为这是在适当的范围(窗口)没有绑定资源的组合。