让 Caliburn.Micro 将我的视图和 VM 绑定到与 Windsor 的单独程序集中
本文关键字:Windsor 单独 程序 集中 程序集 绑定 Micro Caliburn 我的 视图 VM | 更新日期: 2023-09-27 18:32:19
我在这里使用Caliburn.Micro引导程序:
https://gist.github.com/1127914
如果我将所有视图和视图模型与引导器保留在同一个项目中,则一切正常。
但是我想将视图和视图模型文件夹推送到另一个程序集/项目,我确实更改了命名空间,更新引导程序以查找该视图模型。 现在当我运行时,我收到有关
"找不到用于支持服务 MVVMBook.ViewModules.ViewModels.MainViewModel 的组件"
在引导程序的这一部分:
return string.IsNullOrWhiteSpace(key)
? _container.Resolve(service)
: _container.Resolve(key, service);
显然,它无法连接视图模型,即使将虚拟机设置为引导程序的通用参数:
public class CastleBootstrapper : Bootstrapper<MainViewModel>
我使用的命名约定是一个名为Views的文件夹和一个名为ViewModels的文件夹,文件是MainView.xaml和MainViewModel.cs
我在哪里可以告诉它在此程序集中查找?
还将此部分添加到引导程序中,因为当视图和视图模型位于单独的程序集中但未解决问题时,建议使用:
// needed if views and viewmodels are in a seperate assembly
protected override IEnumerable<Assembly> SelectAssemblies()
{
return new[]
{
Assembly.GetExecutingAssembly()
};
}
您的 ViewModel,因为它未注册。引导程序附带的 ApplicationContainer 类有一个 RegisterViewModels 方法,如下所示:
private void RegisterViewModels()
{
Register(AllTypes.FromAssembly(GetType().Assembly)
.Where(x => x.Name.EndsWith("ViewModel"))
.Configure(x => x.LifeStyle.Is(LifestyleType.Transient)));
}
这将仅在应用程序容器所在的程序集中注册 ViewModels。
我想您将这些类粘贴到项目中,以便您可以修改它们。如果是这种情况,您可以修改应用程序容器 RegisterViewModels 或修改 CastleBootstrapper 并覆盖 Configure() 方法,如下所示:
protected override void Configure()
{
_container = new ApplicationContainer();
_container.AddFacility<TypedFactoryFacility>();
_container.Register(AllTypes.FromAssembly(typeof(MainViewModel).Assembly)
.Where(x => x.Name.EndsWith("ViewModel") || x.Name.EndsWith("View"))
.Configure(x => x.LifeStyle.Is(LifestyleType.Transient)));
}
以上将注册所有视图模型和视图。为了使 Caliburn 正确定位视图,请更新 SelectAssemblies() 方法:
protected override IEnumerable<Assembly> SelectAssemblies()
{
return new[]
{
Assembly.GetExecutingAssembly(),
typeof(MainViewModel).Assembly
};
}
更多关于温莎城堡的信息可以在这里找到http://stw.castleproject.org/Windsor.MainPage.ashx