从温莎城堡自动解析
本文关键字:城堡 | 更新日期: 2023-09-27 17:49:22
我试图在不同的程序集中分离我的模型,视图和ViewModel,并使用Castle Windsor实例化它们。
我的app.config
<components>
<component id="ViewModel.SomeViewModel" service="TEST.Business.IViewModel, TEST.Business" type="TEST.ViewModel.SomeViewModel, Test.ViewModel" />
<component id="ViewModel.SomeView" service="TEST.Business.IView, TEST.Business" type="TEST.View.SomeView, Test.View" />
</components>
并通过
解析IoC.Configure();
var viewModel = IoC.Resolve<IViewModel>();
var view = IoC.Resolve<IView>();
view.ShowDialog();
我的静态IoC类
public static class IoC
{
private static IWindsorContainer container;
public static void Configure()
{
IResource resource = new ConfigResource("castle");
container = new WindsorContainer(new XmlInterpreter(resource));
}
public static TService Resolve<TService>()
{
return container.Resolve<TService>();
}
}
直到现在还很简单。
但是我想这样做:
命名必须像这样:I[someName]ViewModel和I[someName]View然后解析我的app.config中的每个组件,从而为每对View和ViewModel解析并关联它们。
我想我的问题有很多解决方案,但我不知道该用哪个关键字。
btw: I[someName]ViewModel和View是ofc IViewModels和IViews
我觉得你做错了。
不要抽象视图和视图模型。它不会给你带来任何好处。因此,问题是架构问题,而不是技术问题。
使用反射遍历要解析的程序集中的类型。您可以使用Classes
进行注册。
var assembly = Assembly.GetExecutingAssembly(); // Replace with the assembly you want to resolve for.
var exports = assembly.ExportedTypes;
var viewTypes = exports.Where(t => t.GetInterface(typeof(IView).FullName) != null);
foreach (var viewType in viewTypes)
{
var viewModelType = assembly.GetType(viewType.FullName.Replace("View", "ViewModel"));
var viewModel = container.Resolve(viewModelType);
var view = container.Resolve(viewType);
view.ShowDialog();
}
在你的例子中,我看不到IViewModel和IView之间的任何依赖关系,所以你的代码没有意义。如果视图模型作为构造函数的参数注入,它将被自动解析。
我不建议使用这种技术。它可能比它需要的更复杂。你确定你真的了解如何使用IoC容器/温莎城堡?
一旦你习惯了Ioc容器,它就很棒。一般来说,您只希望在应用程序的主/引导代码中使用容器。对我来说,似乎您试图使容器的resolve函数静态,以允许在任何地方解析组件。这不应该是必需的。
如果你正在寻找一个方法来绑定视图和视图模型在一个很好的方式,看看caliburn micro。您可以将它与大多数Ioc容器结合使用,包括windsor
亲切的问候,
Marwijn .